philipbohun.com

Glojure by Example: Goroutines

go/go runs a function call on a new goroutine. The argument has to be a call, not a function value: (go/go (worker 1 out)), not (go/go worker).

(defn worker [id out]
  (go/send out (str "worker " id)))

(def out (go/make (go/chan-of go/string) 2))
(go/go (worker 1 out))
(go/go (worker 2 out))

go/recv waits for a value and returns a vector of the value and an open-flag. The workers can finish in either order, so the program sorts their messages before printing.

(let [[a _] (go/recv out)
      [b _] (go/recv out)]
  (doseq [line (sort [a b])]
    (println line)))

future is the smaller tool for a computation with a single result. @ waits for it. The body runs on a goroutine and the result is cached.

(println @(future (+ 20 22)))

Both workers run, and the future prints 42.

$ glj goroutines.glj
worker 1
worker 2
42

Next example: Channels.