(defn get-result-from-first-engine
"Performs search on Powells and Cultura and returns the results
which comes first"
[query]
(let [result (promise)]
(doseq [engine ["powells" "cultura"]]
(future (if-let [engine-result (search query engine)]
(deliver result engine-result)
))
)
(println "First result: " (deref result 2000 "timed out"))
))
(defn -main
[& args]
(time (do
(println (search "clojure" "powells"))
(println (search "clojure" "cultura"))
))
(time (get-result-from-first-engine "clojure"))
)
此代码是我解决《Clojure for the Brave and True》第九章第一练习问题的部分。我想并行执行两个请求,并获取先处理完成的响应。
发生了两件奇怪的事情
- 并行的时间比在main中编写的顺序时间低很多。下面是结果示例。时间差异如此之大,以至于我认为Clojure可能以某种方式进行了缓存。我没有使用memoize或类似的任何东西。
- main不停止运行。它有点像在等待输入或处理某个东西。我的理论是,future不会停止运行,但我不知道为什么
并行和顺序的时间差异
https://www.powells.com/book/clojure-cookbook-9781449366179
https://www3.livrariacultura.com.br/clojure-94991222/p
"Elapsed time: 2185.2716 msecs"
First result: https://www3.livrariacultura.com.br/clojure-94991222/p
"Elapsed time: 63.5558 msecs"
预先感谢您的帮助