atomic package - sync/atomic - Go Packages

Package atomic provides low-level atomic memory primitives useful for implementing synchronization algorithms.

These functions require great care to be used correctly. Except for special, low-level applications, synchronization is better done with channels or the facilities of the sync package. Share memory by communicating; don't communicate by sharing memory.

The swap operation, implemented by the SwapT functions, is the atomic equivalent of:

old = *addr
*addr = new
return old

The compare-and-swap operation, implemented by the CompareAndSwapT functions, is the atomic equivalent of:

if *addr == old {
	*addr = new
	return true
}
return false

The add operation, implemented by the AddT functions, is the atomic equivalent of:

*addr += delta
return *addr

The load and store operations, implemented by the LoadT and StoreT functions, are the atomic equivalents of "return *addr" and "*addr = val".

In the terminology of the Go memory model, if the effect of an atomic operation A is observed by atomic operation B, then A “synchronizes before” B. Additionally, all the atomic operations executed in a program behave as though executed in some sequentially consistent order. This definition provides the same semantics as C++'s sequentially consistent atomics and Java's volatile variables.

This section is empty.

This section is empty.

AddInt32 atomically adds delta to *addr and returns the new value. Consider using the more ergonomic and less error-prone Int32.Add instead.

AddInt64 atomically adds delta to *addr and returns the new value. Consider using the more ergonomic and less error-prone Int64.Add instead (particularly if you target 32-bit platforms; see the bugs section).

AddUint32 atomically adds delta to *addr and returns the new value. To subtract a signed positive constant value c from x, do AddUint32(&x, ^uint32(c-1)). In particular, to decrement x, do AddUint32(&x, ^uint32(0)). Consider using the more ergonomic and less error-prone Uint32.Add instead.

AddUint64 atomically adds delta to *addr and returns the new value. To subtract a signed positive constant value c from x, do AddUint64(&x, ^uint64(c-1)). In particular, to decrement x, do AddUint64(&x, ^uint64(0)). Consider using the more ergonomic and less error-prone Uint64.Add instead (particularly if you target 32-bit platforms; see the bugs section).

AddUintptr atomically adds delta to *addr and returns the new value. Consider using the more ergonomic and less error-prone Uintptr.Add instead.

func AndInt32 added in go1.23.0

AndInt32 atomically performs a bitwise AND operation on *addr using the bitmask provided as mask and returns the old value. Consider using the more ergonomic and less error-prone Int32.And instead.

func AndInt64 added in go1.23.0

AndInt64 atomically performs a bitwise AND operation on *addr using the bitmask provided as mask and returns the old value. Consider using the more ergonomic and less error-prone Int64.And instead.

func AndUint32 added in go1.23.0

AndUint32 atomically performs a bitwise AND operation on *addr using the bitmask provided as mask and returns the old value. Consider using the more ergonomic and less error-prone Uint32.And instead.

func AndUint64 added in go1.23.0

AndUint64 atomically performs a bitwise AND operation on *addr using the bitmask provided as mask and returns the old. Consider using the more ergonomic and less error-prone Uint64.And instead.

func AndUintptr added in go1.23.0

AndUintptr atomically performs a bitwise AND operation on *addr using the bitmask provided as mask and returns the old value. Consider using the more ergonomic and less error-prone Uintptr.And instead.

func CompareAndSwapInt32

CompareAndSwapInt32 executes the compare-and-swap operation for an int32 value. Consider using the more ergonomic and less error-prone Int32.CompareAndSwap instead.

func CompareAndSwapInt64

CompareAndSwapInt64 executes the compare-and-swap operation for an int64 value. Consider using the more ergonomic and less error-prone Int64.CompareAndSwap instead (particularly if you target 32-bit platforms; see the bugs section).

func CompareAndSwapPointer

CompareAndSwapPointer executes the compare-and-swap operation for a unsafe.Pointer value. Consider using the more ergonomic and less error-prone Pointer.CompareAndSwap instead.

func CompareAndSwapUint32

CompareAndSwapUint32 executes the compare-and-swap operation for a uint32 value. Consider using the more ergonomic and less error-prone Uint32.CompareAndSwap instead.

func CompareAndSwapUint64

CompareAndSwapUint64 executes the compare-and-swap operation for a uint64 value. Consider using the more ergonomic and less error-prone Uint64.CompareAndSwap instead (particularly if you target 32-bit platforms; see the bugs section).

func CompareAndSwapUintptr

CompareAndSwapUintptr executes the compare-and-swap operation for a uintptr value. Consider using the more ergonomic and less error-prone Uintptr.CompareAndSwap instead.

LoadInt32 atomically loads *addr. Consider using the more ergonomic and less error-prone Int32.Load instead.

LoadInt64 atomically loads *addr. Consider using the more ergonomic and less error-prone Int64.Load instead (particularly if you target 32-bit platforms; see the bugs section).

LoadPointer atomically loads *addr. Consider using the more ergonomic and less error-prone Pointer.Load instead.

LoadUint32 atomically loads *addr. Consider using the more ergonomic and less error-prone Uint32.Load instead.

LoadUint64 atomically loads *addr. Consider using the more ergonomic and less error-prone Uint64.Load instead (particularly if you target 32-bit platforms; see the bugs section).

LoadUintptr atomically loads *addr. Consider using the more ergonomic and less error-prone Uintptr.Load instead.

OrInt32 atomically performs a bitwise OR operation on *addr using the bitmask provided as mask and returns the old value. Consider using the more ergonomic and less error-prone Int32.Or instead.

OrInt64 atomically performs a bitwise OR operation on *addr using the bitmask provided as mask and returns the old value. Consider using the more ergonomic and less error-prone Int64.Or instead.

OrUint32 atomically performs a bitwise OR operation on *addr using the bitmask provided as mask and returns the old value. Consider using the more ergonomic and less error-prone Uint32.Or instead.

OrUint64 atomically performs a bitwise OR operation on *addr using the bitmask provided as mask and returns the old value. Consider using the more ergonomic and less error-prone Uint64.Or instead.

OrUintptr atomically performs a bitwise OR operation on *addr using the bitmask provided as mask and returns the old value. Consider using the more ergonomic and less error-prone Uintptr.Or instead.

StoreInt32 atomically stores val into *addr. Consider using the more ergonomic and less error-prone Int32.Store instead.

StoreInt64 atomically stores val into *addr. Consider using the more ergonomic and less error-prone Int64.Store instead (particularly if you target 32-bit platforms; see the bugs section).

StorePointer atomically stores val into *addr. Consider using the more ergonomic and less error-prone Pointer.Store instead.

StoreUint32 atomically stores val into *addr. Consider using the more ergonomic and less error-prone Uint32.Store instead.

StoreUint64 atomically stores val into *addr. Consider using the more ergonomic and less error-prone Uint64.Store instead (particularly if you target 32-bit platforms; see the bugs section).

StoreUintptr atomically stores val into *addr. Consider using the more ergonomic and less error-prone Uintptr.Store instead.

SwapInt32 atomically stores new into *addr and returns the previous *addr value. Consider using the more ergonomic and less error-prone Int32.Swap instead.

SwapInt64 atomically stores new into *addr and returns the previous *addr value. Consider using the more ergonomic and less error-prone Int64.Swap instead (particularly if you target 32-bit platforms; see the bugs section).

SwapPointer atomically stores new into *addr and returns the previous *addr value. Consider using the more ergonomic and less error-prone Pointer.Swap instead.

SwapUint32 atomically stores new into *addr and returns the previous *addr value. Consider using the more ergonomic and less error-prone Uint32.Swap instead.

SwapUint64 atomically stores new into *addr and returns the previous *addr value. Consider using the more ergonomic and less error-prone Uint64.Swap instead (particularly if you target 32-bit platforms; see the bugs section).

SwapUintptr atomically stores new into *addr and returns the previous *addr value. Consider using the more ergonomic and less error-prone Uintptr.Swap instead.

A Bool is an atomic boolean value. The zero value is false.

Bool must not be copied after first use.

func (*Bool) CompareAndSwap added in go1.19

func (x *Bool) CompareAndSwap(old, new bool) (swapped bool)

CompareAndSwap executes the compare-and-swap operation for the boolean value x.

func (x *Bool) Load() bool

Load atomically loads and returns the value stored in x.

func (x *Bool) Store(val bool)

Store atomically stores val into x.

Swap atomically stores new into x and returns the previous value.

An Int32 is an atomic int32. The zero value is zero.

Int32 must not be copied after first use.

Add atomically adds delta to x and returns the new value.

func (*Int32) And added in go1.23.0

And atomically performs a bitwise AND operation on x using the bitmask provided as mask and returns the old value.

func (*Int32) CompareAndSwap added in go1.19

func (x *Int32) CompareAndSwap(old, new int32) (swapped bool)

CompareAndSwap executes the compare-and-swap operation for x.

Load atomically loads and returns the value stored in x.

Or atomically performs a bitwise OR operation on x using the bitmask provided as mask and returns the old value.

Store atomically stores val into x.

Swap atomically stores new into x and returns the previous value.

An Int64 is an atomic int64. The zero value is zero.

Int64 must not be copied after first use.

Add atomically adds delta to x and returns the new value.

func (*Int64) And added in go1.23.0

And atomically performs a bitwise AND operation on x using the bitmask provided as mask and returns the old value.

func (*Int64) CompareAndSwap added in go1.19

func (x *Int64) CompareAndSwap(old, new int64) (swapped bool)

CompareAndSwap executes the compare-and-swap operation for x.

Load atomically loads and returns the value stored in x.

Or atomically performs a bitwise OR operation on x using the bitmask provided as mask and returns the old value.

Store atomically stores val into x.

Swap atomically stores new into x and returns the previous value.

type Pointer[T any] struct {
	
}

A Pointer is an atomic pointer of type *T. The zero value is a nil *T.

Pointer must not be copied after first use.

func (*Pointer[T]) CompareAndSwap added in go1.19

func (x *Pointer[T]) CompareAndSwap(old, new *T) (swapped bool)

CompareAndSwap executes the compare-and-swap operation for x.

func (x *Pointer[T]) Load() *T

Load atomically loads and returns the value stored in x.

func (x *Pointer[T]) Store(val *T)

Store atomically stores val into x.

func (x *Pointer[T]) Swap(new *T) (old *T)

Swap atomically stores new into x and returns the previous value.

A Uint32 is an atomic uint32. The zero value is zero.

Uint32 must not be copied after first use.

Add atomically adds delta to x and returns the new value.

func (*Uint32) And added in go1.23.0

And atomically performs a bitwise AND operation on x using the bitmask provided as mask and returns the old value.

func (*Uint32) CompareAndSwap added in go1.19

func (x *Uint32) CompareAndSwap(old, new uint32) (swapped bool)

CompareAndSwap executes the compare-and-swap operation for x.

Load atomically loads and returns the value stored in x.

Or atomically performs a bitwise OR operation on x using the bitmask provided as mask and returns the old value.

Store atomically stores val into x.

Swap atomically stores new into x and returns the previous value.

A Uint64 is an atomic uint64. The zero value is zero.

Uint64 must not be copied after first use.

Add atomically adds delta to x and returns the new value.

func (*Uint64) And added in go1.23.0

And atomically performs a bitwise AND operation on x using the bitmask provided as mask and returns the old value.

func (*Uint64) CompareAndSwap added in go1.19

func (x *Uint64) CompareAndSwap(old, new uint64) (swapped bool)

CompareAndSwap executes the compare-and-swap operation for x.

Load atomically loads and returns the value stored in x.

Or atomically performs a bitwise OR operation on x using the bitmask provided as mask and returns the old value.

Store atomically stores val into x.

Swap atomically stores new into x and returns the previous value.

A Uintptr is an atomic uintptr. The zero value is zero.

Uintptr must not be copied after first use.

Add atomically adds delta to x and returns the new value.

func (*Uintptr) And added in go1.23.0

And atomically performs a bitwise AND operation on x using the bitmask provided as mask and returns the old value.

func (*Uintptr) CompareAndSwap added in go1.19

CompareAndSwap executes the compare-and-swap operation for x.

Load atomically loads and returns the value stored in x.

Or atomically performs a bitwise OR operation on x using the bitmask provided as mask and returns the old value.

Store atomically stores val into x.

Swap atomically stores new into x and returns the previous value.

A Value provides an atomic load and store of a consistently typed value. The zero value for a Value returns nil from Value.Load. Once Value.Store has been called, a Value must not be copied.

A Value must not be copied after first use.

The following example shows how to use Value for periodic program config updates and propagation of the changes to worker goroutines.

package main

import (
	"sync/atomic"
	"time"
)

func loadConfig() map[string]string {
	return make(map[string]string)
}

func requests() chan int {
	return make(chan int)
}

func main() {
	var config atomic.Value // holds current server configuration
	// Create initial config value and store into config.
	config.Store(loadConfig())
	go func() {
		// Reload config every 10 seconds
		// and update config value with the new version.
		for {
			time.Sleep(10 * time.Second)
			config.Store(loadConfig())
		}
	}()
	// Create worker goroutines that handle incoming requests
	// using the latest config value.
	for i := 0; i < 10; i++ {
		go func() {
			for r := range requests() {
				c := config.Load()
				// Handle request r using config c.
				_, _ = r, c
			}
		}()
	}
}

The following example shows how to maintain a scalable frequently read, but infrequently updated data structure using copy-on-write idiom.

package main

import (
	"sync"
	"sync/atomic"
)

func main() {
	type Map map[string]string
	var m atomic.Value
	m.Store(make(Map))
	var mu sync.Mutex // used only by writers
	// read function can be used to read the data without further synchronization
	read := func(key string) (val string) {
		m1 := m.Load().(Map)
		return m1[key]
	}
	// insert function can be used to update the data without further synchronization
	insert := func(key, val string) {
		mu.Lock() // synchronize with other potential writers
		defer mu.Unlock()
		m1 := m.Load().(Map) // load current value of the data structure
		m2 := make(Map)      // create a new value
		for k, v := range m1 {
			m2[k] = v // copy all data from the current object to the new one
		}
		m2[key] = val // do the update that we need
		m.Store(m2)   // atomically replace the current object with the new one
		// At this point all new readers start working with the new version.
		// The old version will be garbage collected once the existing readers
		// (if any) are done with it.
	}
	_, _ = read, insert
}

func (*Value) CompareAndSwap added in go1.17

func (v *Value) CompareAndSwap(old, new any) (swapped bool)

CompareAndSwap executes the compare-and-swap operation for the Value.

All calls to CompareAndSwap for a given Value must use values of the same concrete type. CompareAndSwap of an inconsistent type panics, as does CompareAndSwap(old, nil).

func (v *Value) Load() (val any)

Load returns the value set by the most recent Store. It returns nil if there has been no call to Store for this Value.

func (v *Value) Store(val any)

Store sets the value of the Value v to val. All calls to Store for a given Value must use values of the same concrete type. Store of an inconsistent type panics, as does Store(nil).

func (v *Value) Swap(new any) (old any)

Swap stores new into Value and returns the previous value. It returns nil if the Value is empty.

All calls to Swap for a given Value must use values of the same concrete type. Swap of an inconsistent type panics, as does Swap(nil).

  • On 386, the 64-bit functions use instructions unavailable before the Pentium MMX.

    On non-Linux ARM, the 64-bit functions use instructions unavailable before the ARMv6k core.

    On ARM, 386, and 32-bit MIPS, it is the caller's responsibility to arrange for 64-bit alignment of 64-bit words accessed atomically via the primitive atomic functions (types Int64 and Uint64 are automatically aligned). The first word in an allocated struct, array, or slice; in a global variable; or in a local variable (because on 32-bit architectures, the subject of 64-bit atomic operations will escape to the heap) can be relied upon to be 64-bit aligned.