Use typed atomics and CAS
Use typed atomics and CAS
Typed atomics from sync/atomic provide indivisible operations on individual values. CompareAndSwap (CAS) changes a value only if it equals the expected old value. Use atomic counters for independent metrics, not as automatic protection for multiple related fields.
package main
import ( "fmt" "sync" "sync/atomic")
func main() { var n atomic.Int64 var wg sync.WaitGroup for i := 0; i < 5; i++ { wg.Add(1) go func() { defer wg.Done(); n.Add(2) }() } wg.Wait() fmt.Println(n.Load())}Add combines the read and update. Separate Load and Store can lose updates even if each is atomic. Typed atomics introduced in Go 1.19 start at zero and must not be copied after first use. Go atomic operations behave as if executed in a sequentially consistent order. Do not mix ordinary unsynchronized access with atomic access to the same storage.
Expected output:
10Compare and swap state
package main
import ( "fmt" "sync/atomic")
func main() { var state atomic.Int32 state.Store(1) fmt.Println(state.CompareAndSwap(1, 2)) fmt.Println(state.CompareAndSwap(1, 3)) fmt.Println(state.Load())}The second CAS fails because the current value is 2. In a retry loop, load and recompute after failure; avoid repeating side effects. CAS tests equality, not whether an intervening change was reversed (the ABA problem). For multi-field invariants prefer a lock.
Expected output:
truefalse2Try it locally
Use atomic.Bool to permit the first transition from false to true. Print two CAS results and the final value, one per line: true, false, true.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Synchronization 07: Use typed atomics and CAS
Check the lesson objective before moving on.
Which operation prevents lost increments?
Does CAS guarantee that no intervening change occurred?