Standard library / sync/atomic

atomic.CompareAndSwapUint32()

Atomically replace the value only if it equals old. CAS does not by itself protect multi-variable invariants. Raw pointer APIs require correctly aligned storage; prefer the corresponding typed atomic in new code. Expected stdout: 'true\n15\n'.

Formal Syntax & Structure

go syntaxgo
func CompareAndSwapUint32(addr *uint32, old, new uint32) (swapped bool)

Parameters & Attributes

NameTypeDescription
addr*uint32Pointer to the shared variable; satisfy architecture alignment requirements and use atomic access consistently.
olduint32Expected current value for comparison.
newuint32Replacement value.

Return Value

(swapped bool)

Whether the value matched and was replaced.

Working Example

Example Snippetgo
package main
import (  "fmt"  "sync/atomic")
func main() {  x := new(uint32)  atomic.StoreUint32(x, 12)  fmt.Println(atomic.CompareAndSwapUint32(x, 12, 15))  fmt.Println(atomic.LoadUint32(x))}
Go Reference