HowtoGo
Home / Concurrency / Atomic Operations
Concurrency

Atomic Operations

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
100
FunctionDescription
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