philipbohun.com

Glojure by Example: Wait Groups

sync.WaitGroup waits until a set of goroutines has called Done. Call Add before starting the goroutine. go/go runs a call, so the worker is an ordinary function.

(def wg (new sync.WaitGroup))
(def seen (atom []))

(defn worker [id]
  (swap! seen conj id)
  (.Done wg))

(doseq [id [0 1 2]]
  (.Add wg 1)
  (go/go (worker id)))

(.Wait wg)
(println (sort @seen))

Wait returns after every Done. The ids are sorted because completion order is not fixed.

$ glj wait-groups.glj
(0 1 2)

Next example: Rate Limiting.