philipbohun.com

Glojure by Example: Atomic Counters

sync/atomic updates a number in place. The counter is a pointer from go/new, because the Go functions take *int64. Five goroutines each add 100.

(def ops (go/new go/int64))
(def wg (new sync.WaitGroup))

(defn worker []
  (dotimes [_ 100]
    (sync:atomic.AddInt64 ops 1))
  (.Done wg))

(dotimes [_ 5]
  (.Add wg 1)
  (go/go (worker)))

(.Wait wg)
(println (go/deref ops))

An atom is the better counter for Clojure code. Reach for sync/atomic when the number is a Go value shared with Go APIs.

5 workers times 100 increments.

$ glj atomic-counters.glj
500

Next example: Mutexes.