philipbohun.com

Glojure by Example: Mutexes

sync.Mutex locks a region so only one goroutine runs it at a time. This map is a Go map, which is not safe for concurrent use on its own. The lock covers the read and the write together. Values are go/int64 so they match Glojure integers.

(def accounts (go/make (go/map-of go/string go/int64)))
(def mu (new sync.Mutex))
(def wg (new sync.WaitGroup))

(go/set-map-index accounts "ada" 0)

(defn deposit []
  (.Lock mu)
  (go/set-map-index accounts "ada"
    (+ (go/map-index accounts "ada") 1))
  (.Unlock mu)
  (.Done wg))

swap! on a single atom is already atomic, so a mutex around one atom adds nothing. Use the mutex when the protected thing is a Go value, or when several updates must happen together. Reading a missing Go map key panics, so the key is created before the workers start.

(dotimes [_ 50]
  (.Add wg 1)
  (go/go (deposit)))
(.Wait wg)
(println (go/map-index accounts "ada"))

Fifty deposits under the lock land in the map.

$ glj mutexes.glj
50

Next example: Stateful Goroutines.