(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"
非常感谢提前的帮助