[Golang (Go)] Use sync/atomic package to provides low-level atomic memory primitives useful for implementing synchronization

sync/atomic

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.

Examples

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

1
2
3
old = *addr
*addr = new
return old
1
func SwapInt32(addr *int32, new int32) (old int32)

SwapInt32 atomically stores new into *addr and returns the previous *addr value.

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

1
2
3
4
5
if *addr == old {
*addr = new
return true
}
return false
1
func CompareAndSwapInt32(addr *int32, old, new int32) (swapped bool)

CompareAndSwapInt32 executes the compare-and-swap operation for an int32 value.

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

1
2
*addr += delta
return *addr
1
func AddInt32(addr *int32, delta int32) (new int32)

AddInt32 atomically adds delta to *addr and returns the new value.

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

1
func LoadInt32(addr *int32) (val int32)

LoadInt32 atomically loads *addr.

1
func StoreInt32(addr *int32, val int32)

StoreInt32 atomically stores val into *addr.

See atomic - The Go Programming Language - https://golang.org/pkg/sync/atomic/ to learn more methods.

References

[1] atomic - The Go Programming Language - https://golang.org/pkg/sync/atomic/