The sync/atomic package updates integers, booleans, and values without a lock, safe for concurrent use from any number of goroutines.
Examples
atomic.Int64 replaces int64 plus a mutex for a simple counter. Add is safe from any number of goroutines at once.
var counter atomic.Int64
var wg sync.WaitGroup
for i := 0; i < 100; i++ {
wg.Add(1)
go func() {
defer wg.Done()
counter.Add(1)
}()
}
wg.Wait()
fmt.Println(counter.Load())Output
100CompareAndSwap only writes when the current value matches old. A false return means another goroutine already changed it.
var state atomic.Int32
state.Store(1)
swapped := state.CompareAndSwap(1, 2)
fmt.Println(swapped, state.Load())
swapped = state.CompareAndSwap(1, 3)
fmt.Println(swapped, state.Load())Output
true 2
false 2atomic.Bool covers a simple flag. atomic.Value holds any type behind Load/Store, useful for swapping a whole config without a lock.
var ready atomic.Bool
go func() {
ready.Store(true)
}()
for !ready.Load() {
} // polling for illustration; use a channel in real code
fmt.Println("ready")
var config atomic.Value
config.Store(map[string]int{"workers": 4})
cfg := config.Load().(map[string]int)
fmt.Println(cfg["workers"])Output
ready
4The typed wrappers sit on top of this older, pointer-based API. New code should use atomic.Int64 and friends; the functions remain for existing *int64 fields.
var x int64
atomic.AddInt64(&x, 5)
atomic.CompareAndSwapInt64(&x, 5, 10)
fmt.Println(atomic.LoadInt64(&x))Output
10| Function | Description |
|---|---|
Add(delta) counter.Add(1) | Adds delta and returns the new value |
Load() counter.Load() | Reads the current value atomically |
Store(v) counter.Store(5) | Sets the value atomically |
Swap(new) counter.Swap(10) | Sets new, returns the value it replaced |
CompareAndSwap(old, new) counter.CompareAndSwap(0, 1) | Swaps only if the current value equals old |
atomic.Bool / Int32 / Int64 / Uint32 / Uint64 var n atomic.Int64 | Typed wrappers, Go 1.19+ |
atomic.Value var v atomic.Value | Atomic Load/Store for any type |
Related: Goroutines Mutexes Worker Pools