Skip to content

Instantly share code, notes, and snippets.

@issadarkthing
Last active October 1, 2020 03:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save issadarkthing/6e534a5dc830ddbc237d5f4370544c58 to your computer and use it in GitHub Desktop.
Save issadarkthing/6e534a5dc830ddbc237d5f4370544c58 to your computer and use it in GitHub Desktop.
Clojure function that evaluates long running functions and wait for all functions return.
(ns script
(:require [clojure.core.async :as async]))
(defn long-computation
"simulate long running operation"
[x]
(Thread/sleep 1000)
(rand-int x))
(defn wait-all
"wait-all takes sequence of long running functions and wait for all
functions to complete, returns vector of values.
It does not wait sequentially which produces
non-deterministic sequence."
[fns]
(let [chans (map (fn [f] (async/go (f))) fns)
fn-length (count fns)
acc-chans (async/merge chans)]
(loop [i fn-length result '()]
(if (zero? i)
result
(recur (dec i) (cons (async/<!! acc-chans) result))))))
(time (wait-all
; create 100 functions with 1s delay
(repeat 100 (partial long-computation 10))))
; we managed to complete all functions and retrieve the values asynchronously
;=> "Elapsed time: 1004.285832 msecs"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment