Atomic Counters
Use typed sync/atomic operations for independent counter updates and reads across goroutines.
A data race happens when goroutines, function calls started with go, use the same variable at the same time and at least one changes it without coordination. A counter increment reads, adds one, then writes the result. If two goroutines do this together, one update can be lost. The sync/atomic package provides operations that change a value in one step, so another goroutine cannot see a half-finished update.
atomic.Int64 is a 64-bit integer counter designed for safe use by multiple goroutines. Add increments it, and Load reads its current value.
package main
import (
"fmt"
"sync"
"sync/atomic"
)
func main() {
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())
}In production
Atomic operations work well for a single counter or yes/no flag. They cannot change several related values together. Use a mutex, a lock that lets only one goroutine at a time change shared data, when several values must stay in sync.