Last active
December 19, 2015 17:28
Short-circuiting logical conjunction of several futures' values
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(defn thread-and | |
"Computes logical conjunction of return values of fs, each of which | |
is called in a future. Short-circuits (cancelling the remaining | |
futures) on first falsey value." | |
[& fs] | |
(let [done (promise) | |
ret (atom true) | |
fps (promise)] | |
(deliver fps (doall (for [f fs] | |
(let [p (promise)] | |
[(future | |
(if-not (swap! ret #(and %1 %2) (f)) | |
(deliver done true)) | |
(locking fps | |
(deliver p true) | |
(when (every? realized? (map peek @fps)) | |
(deliver done true)))) | |
p])))) | |
@done | |
(doseq [[fut] @fps] | |
(future-cancel fut)) | |
@ret)) | |
(comment | |
(thread-and (constantly true) (constantly true)) | |
;;= true | |
(thread-and (constantly true) (constantly false)) | |
;;= false | |
(every? false? | |
(repeatedly 100000 | |
#(thread-and (constantly true) (constantly false)))) | |
;;= true | |
;; prints :foo, but not :bar | |
(thread-and #(do (Thread/sleep 1000) (println :foo)) | |
#(do (Thread/sleep 3000) (println :bar))) | |
) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment