Logo

Programming-Idioms

This language bar is your friend. Select your favorite languages!
  • Go

Idiom #33 Atomically read and update variable

Assign to the variable x the new value f(x), making sure that no other thread may modify x between the read and the write.

import "sync"
var lock sync.Mutex

lock.Lock()
x = f(x)
lock.Unlock()

You need to lock whenever accessing x.
(def x (atom 0))
(def f inc)
(swap! x f)

New implementation...
< >
programming-idioms.org