Atomics
The sync/atomic package provides atomic load, store, add, and compare-and-swap on integers and pointers. A single atomic operation is indivisible: another goroutine sees the old value or the new one, not a torn write.
Detailed Explanation
n++ on an int shared by two goroutines is a race: read-modify-write is three steps. atomic.AddInt64(&n, 1) is one operation the CPU guarantees. Use atomics for counters, flags, and swapping a pointer to an immutable snapshot. Do not use them to stitch together a multi-field invariant — that is a mutex.
The typed API. Go 1.19 added atomic.Int64, atomic.Bool, atomic.Pointer[T]. var n atomic.Int64; n.Add(1); v := n.Load() is harder to misuse than atomic.AddInt64 on a raw int64 you might accidentally read with n. Prefer the types.
Memory order. Go's atomics are sequentially consistent enough for the usual patterns: a store that publishes a pointer happens-before a load that sees that pointer, and the pointee's writes that preceded the store are visible. You do not pick memory_order_relaxed as in C++. If you need a documented happens-before for several fields, use a mutex or swap one pointer to a whole struct.
CAS loops. CompareAndSwap is the building block for lock-free updates: load, compute, CAS, retry on failure. They are easy to get wrong under contention. A mutex is the default; a CAS loop is for when you measured the mutex and know the update is a single word.
What it costs. An uncontended atomic is cheaper than a mutex. A hot CAS loop can be slower than a mutex because it retries. Mixing atomic and non-atomic access to the same word is a race. The race detector understands sync/atomic; it does not treat a plain n++ as atomic.
Code Examples
package main
import (
"fmt"
"sync/atomic"
)
func main() {
var n atomic.Int64
n.Add(1)
fmt.Println(n.Load())
}func storeFlag(done *atomic.Bool) {
done.Store(true)
}
func spin(done *atomic.Bool) {
for !done.Load() {
}
}func casAdd(p *atomic.Int64, delta int64) {
for {
old := p.Load()
if p.CompareAndSwap(old, old+delta) {
return
}
}
}Common Gotchas
Reading an atomic word with a plain load is a data race
use `Load` on every path.
Two atomics do not make a transaction
`Load` A then `Store` B can interleave with another goroutine.
A spin on `Load` burns CPU
wait on a channel or `Cond` if the wait can be long.
`int` is not an atomic type
use `Int64` or `Uintptr`, not a raw `int` on a 32-bit platform if you need a 64-bit counter.