(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"))
)
This code is part of my solution to the first exercise from chapter 9 of "Clojure for the Brave and True". I want to perform the two requests in parallel and get the response of the one who process first.
Two weird things are happening:
- The time from the parallel is WAY lower than the sequential one, written in main. Result example below. The time difference is so discrepant, that i guess if clojure caches it someway. I didn't use memoize or anything like that.
- The main doesn't stop running. It holds like if it was waiting for an input or processing something. My theory is that the future doesn't stop running, but i don't know why
Time difference between parallel and sequential:
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"
Thanks for the help in advance