(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”第9章第一个练习的解决方案的一部分。我想并行执行两个请求,并获取先处理完的请求的响应。
出现了两个奇怪的事情
- 并行的时间远远低于主程序中的顺序执行时间。以下是其结果示例。这种时间差异如此之大,以至于我猜测Clojure可能在某种程度上进行了缓存。我没有使用memoize之类的任何东西。
- 主程序没有停止运行。它保持在一种似乎是等待输入或处理某事的状态。我的理论是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"
感谢提前帮忙