Standard library / sync/atomic
atomic.CompareAndSwapInt32()
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 CompareAndSwapInt32(addr *int32, old, new int32) (swapped bool)Parameters & Attributes
| Name | Type | Description |
|---|---|---|
| addr | *int32 | Pointer to the shared variable; satisfy architecture alignment requirements and use atomic access consistently. |
| old | int32 | Expected current value for comparison. |
| new | int32 | 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(int32) atomic.StoreInt32(x, 12) fmt.Println(atomic.CompareAndSwapInt32(x, 12, 15)) fmt.Println(atomic.LoadInt32(x))}