Source file src/sync/counter.go

     1  // Copyright 2026 The Go Authors. All rights reserved.
     2  // Use of this source code is governed by a BSD-style
     3  // license that can be found in the LICENSE file.
     4  
     5  package sync
     6  
     7  import (
     8  	"sync/atomic"
     9  	"unsafe"
    10  )
    11  
    12  // Counter is a concurrent counter of int64, uint64, or float64 values.
    13  //
    14  // Counter is specialized for frequent, contended writes and infrequent
    15  // reads. Prefer Counter over a [sync/atomic] or [Mutex] protected counter for
    16  // improved performance when writes are much more common than reads,
    17  // and approximate (unsynchronized) reads are acceptable for the
    18  // use case. Value takes time proportional to the maximum GOMAXPROCS
    19  // seen by the counter.
    20  //
    21  // The zero Counter has value 0 and is ready for use.
    22  // A Counter must not be copied after first use.
    23  type Counter[T ~float64 | ~int64 | ~uint64] struct {
    24  	cache stripe
    25  }
    26  
    27  // Add adds delta to the counter.
    28  //
    29  // In the terminology of [the Go memory model], Add is NOT synchronized before
    30  // calls to Add or [Counter.Value] on other goroutines.
    31  // Callers must not rely on Add as a memory barrier or synchronization
    32  // primitive to publish or synchronize access to other non-counter memory
    33  // mutations.
    34  //
    35  // For integer types, overflow wraps around, the same as [integer overflow]
    36  // defined in the Go Language Specification.
    37  //
    38  // For floating-point types, additions are accumulated in arbitrary
    39  // order, so rounding and overflow may differ from sequential addition.
    40  //
    41  // [the Go memory model]: https://go.dev/ref/mem
    42  // [integer overflow]: https://go.dev/ref/spec#Integer_overflow
    43  func (c *Counter[T]) Add(delta T) {
    44  	// Pinning to a P ensures no other goroutine writes to the
    45  	// returned shard until we unpin, so the load need not be atomic.
    46  	pID := runtime_procPin()
    47  	n := c.cache.get(pID)
    48  	newVal := *(*T)(unsafe.Pointer(n)) + delta
    49  	// Store atomically so concurrent Value loads cannot tear or race.
    50  	atomic.StoreUint64(n, *(*uint64)(unsafe.Pointer(&newVal)))
    51  	runtime_procUnpin()
    52  }
    53  
    54  // Value returns the sum of the values added to the counter.
    55  //
    56  // Value and [Counter.Add] may be called concurrently.
    57  //
    58  // In the terminology of [the Go memory model], [Counter.Add] is NOT
    59  // synchronized before Value. In other words, Value observes an arbitrary
    60  // subset of concurrent [Counter.Add] calls. Informally, Value returns only an
    61  // approximate sum of all [Counter.Add] calls.
    62  //
    63  // While callers may use external synchronization to make [Counter.Add]
    64  // synchronized before Value, note that the sum still occurs in an
    65  // arbitrary order. For float64, the value may still differ from
    66  // sequential addition due to rounding or overflow.
    67  //
    68  // Value takes time proportional to GOMAXPROCS.
    69  //
    70  // [the Go memory model]: https://go.dev/ref/mem
    71  func (c *Counter[T]) Value() T {
    72  	var sum T
    73  	s := &c.cache
    74  	stripeCap := s.cap()
    75  	block := unsafe.Slice(s.block.Load(), stripeCap)
    76  
    77  	for i := range stripeCap {
    78  		n := block[i]
    79  		// Load atomically to prevent tearing and races with concurrent Add.
    80  		v := atomic.LoadUint64(n)
    81  		sum += *(*T)(unsafe.Pointer(&v))
    82  	}
    83  	return sum
    84  }
    85  

View as plain text