Atomic counters
Context
Section titled “Context”The sync/atomic package provides low‑level atomic memory operations for integers and pointers. Use them to increment counters without locks.
Example
Section titled “Example”Increment a counter from multiple goroutines using atomic.AddUint64.
Code example
Section titled “Code example”package main
import ( "fmt" "sync" "sync/atomic")
func main() { var counter uint64 var wg sync.WaitGroup
for i := 0; i < 1000; i++ { wg.Add(1) go func() { atomic.AddUint64(&counter, 1) wg.Done() }() } wg.Wait() fmt.Println("counter:", counter)}Output
Section titled “Output”counter: 1000