Last active
October 1, 2020 03:44
-
-
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.
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
(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