Go core
Browse topics

Atomic counters

Version
1.27
Since
1.19
Review
Draft

Summary#

atomic.Int64 lets goroutines update one integer safely without a mutex. Add adds a delta, Load reads the value, and CompareAndSwap replaces it if its current value matches the expected value.

Syntax#

go
var counter atomic.Int64
counter.Add(1)
current := counter.Load()
swapped := counter.CompareAndSwap(current, next)

Example#

go
package main

import (
	"fmt"
	"sync"
	"sync/atomic"
)

func storeMax(highest *atomic.Int64, value int64) {
	for {
		current := highest.Load()
		if value <= current || highest.CompareAndSwap(current, value) {
			return
		}
		// Another goroutine changed it. Try again.
	}
}

func main() {
	var total, highest atomic.Int64
	var group sync.WaitGroup
	for size := range int64(100) {
		group.Go(func() {
			total.Add(size)
			storeMax(&highest, size)
		})
	}
	group.Wait()

	fmt.Println(total.Load(), highest.Load())
}

Expected output#

Text
4950 99

Common mistakes#

counter.Store(counter.Load() + 1) is two operations and can lose updates. Use Add. Separate atomic variables do not change together, so guard related values with a mutex. Do not copy an atomic value after first use.

Version applicability#

The atomic.Int64 type was added in Go 1.19. Earlier versions use functions such as atomic.AddInt64 on a properly aligned int64 variable. Integer range requires Go 1.22, and WaitGroup.Go makes the complete example require Go 1.25 or later.

Sources#

Attribution
DevLookup contributors
License
CC-BY-4.0