Is there a Clojure idiom for dispatching multiple expressions in parallel
clojure, concurrency
Solution
Here's my take on it.
Basically you have to resolve a global promise inside each of your futures, then return a vector containing future list and the resolved value and then cancel all the futures in the list:
(defn run-and-cancel [& expr]
(let [p (promise)
run-futures (fn [& expr] [(doall (map #(future (deliver p (eval %1))) expr)) @p])
[fs res] (apply run-futures expr)]
(map future-cancel fs)
res))
Problem
I have a number of (unevaluated) expressions held in a vector; [ expr1 expr2 expr3 ... ] What I wish to do is hand each expression to a separate thread and wait until one returns a value. At that point I'm not interested in the results from the other threads and would like to cancel them to save CPU resource. ( I realise that this could cause non-determinism in that different runs of the program might cause different expressions to be evaluated first. I have this in hand. ) Is there a standard / idiomatic way of achieving the above?