Skip to content

Instantly share code, notes, and snippets.

@logosity
Created August 9, 2013 20:09
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save logosity/6196767 to your computer and use it in GitHub Desktop.
Block a caller on any number of long-running/non-terminating functions continuing when any one of them returns (the others will run to completion, or presumably get cleaned up by the calling context):
;;; block caller until any one of the passed functions complets and return its result
(defn wait-any [& fns]
(let [p (promise)]
(doseq [f fns] (future (deliver p (f))))
(deref p)))
;;; (wait-any #(do (Thread/sleep 4000) 1) #(do (Thread/sleep 2000) 2) #(do (Thread/sleep 3000) 3))
;;; output: 2
@swannodette
Copy link

(defn task [f] (go (f)))

(defn wait-any [& fs]
  (first (alts!! (into [] (map task fs)))))

;; (wait-any #(do (Thread/sleep 4000) 1) #(do (Thread/sleep 2000) 2) #(do (Thread/sleep 3000) 3))
;; output: 2

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment