Standard library / sync/atomic

atomic.CompareAndSwapInt64()

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 CompareAndSwapInt64(addr *int64, old, new int64) (swapped bool)

Parameters & Attributes

NameTypeDescription
addr*int64Pointer to the shared variable; satisfy architecture alignment requirements and use atomic access consistently.
oldint64Expected current value for comparison.
newint64Replacement 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(int64)  atomic.StoreInt64(x, 12)  fmt.Println(atomic.CompareAndSwapInt64(x, 12, 15))  fmt.Println(atomic.LoadInt64(x))}
Go Reference
atomic.CompareAndSwapInt64() — Go Syntax & | ByteMind