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
| Name | Type | Description |
|---|---|---|
| addr | *uint32 | Pointer to the shared variable; satisfy architecture alignment requirements and use atomic access consistently. |
| old | uint32 | Expected current value for comparison. |
| new | uint32 | Replacement 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))}