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

NameTypeDescription
addr*int32Pointer to the shared variable; satisfy architecture alignment requirements and use atomic access consistently.
oldint32Expected current value for comparison.
newint32Replacement 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))}
Go Reference