Skip to content

Atomic counters

The sync/atomic package provides low‑level atomic memory operations for integers and pointers. Use them to increment counters without locks.

Increment a counter from multiple goroutines using atomic.AddUint64.

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)
}
Terminal window
counter: 1000