philipbohun.com

Glojure by Example: Worker Pools

A pool is a fixed set of goroutines reading from one jobs channel and writing to one results channel. Closing the jobs channel tells every worker to exit after it has drained the work.

(require '[clojure.core.async :as async])

(def jobs (async/chan 5))
(def results (async/chan 5))

(defn worker []
  (loop []
    (when-let [job (async/<! jobs)]
      (async/>! results (* job 2))
      (recur))))

(dotimes [_ 3]
  (async/go (worker)))

The main flow sends five jobs, closes the jobs channel, and collects five results. Sorting them makes the printout independent of which worker finished first.

(doseq [job [1 2 3 4 5]]
  (async/>! jobs job))
(async/close! jobs)

(println (sort (loop [n 5
                      acc []]
                 (if (zero? n)
                   acc
                   (recur (dec n) (conj acc (async/<! results)))))))

Each job is doubled.

$ glj worker-pools.glj
(2 4 6 8 10)

Next example: Wait Groups.