When several threads update a shared counter, a lock is not the only option. swap accepts a function, computes a new value from the current one, and installs it only if that value has not changed. section 8.2
The operation proceeds by retrying contested updates:
- Read the atom's current value. section 8.2
- Compute the next value by calling the supplied function. section 8.2
- Compare the value with the original snapshot and retry if another update intervened. section 8.2
Incrementing a shared counter
Initialize an atom with zero, then call counter.swap(function(x) { return x + 1; }) for each database access. Read the total with counter.get().
