Add sharded Counter type for scalable concurrent counting
A single atomic counter becomes a bottleneck on machines with many CPUs, because every update fights over the same cache line. The new generic sync.Counter type splits the counter into per-CPU shards (one per P, up to GOMAXPROCS). It is meant for counters that are updated often and read rarely.
Concurrent Add calls update only their local shard, so writes stay fast under heavy contention. Value sums all shards, so its cost grows with GOMAXPROCS. It is race-free, but while writers are active it returns an approximate total, not a consistent snapshot. Add does not create a happens-before relationship, so don't use it for synchronization. Overflow wraps around. If GOMAXPROCS shrinks, existing shards are kept, so no counts are lost.
var requests sync.Counter[int64]
func handle() {
requests.Add(1) // fast, even from many goroutines
}
func report() {
fmt.Println(requests.Value()) // slower; approximate under concurrent writes
}
The type parameter accepts ~int64, ~uint64, and ~float64.
- Proposal
- #80645 by cagedmantis
- Status
- Implemented on Nov 23, 2026
- Release
- Go 1.28
- Impact
- medium
- Area
- sync