How CompareAndSwap it works?
Parameters:
addr: a pointer to anint32variableoldval: the expected value of theint32variablenewval: the new value to be stored in theint32variable
Return value:
swapped: a boolean indicating whether the swap was successful (i.e., the value was updated)
How it works:
- The function loads the current value of the
int32variable pointed to byaddrinto a register. - It compares the loaded value with the
oldvalparameter. If they match, it proceeds to step 3. - It stores the
newvalparameter in theint32variable pointed to byaddr. - It returns
trueif the swap was successful (i.e., the value was updated), andfalseotherwise.
Here's an example of how you might use CompareAndSwapInt32:
package main
import (
"fmt"
"sync/atomic"
)
var counter int32
func main() {
for i := 0; i < 10; i++ {
if atomic.CompareAndSwapInt32(&counter, 0, 1) {
fmt.Println("Counter incremented successfully")
} else {
fmt.Println("Counter not incremented (another goroutine got there first)")
}
}
}
Here are some reasons why atomic.CompareAndSwap functions are concurrency-safe:
- Memory barriers: The atomic package uses memory barriers to ensure that the CPU cache is updated correctly. This prevents the CPU from caching the old value of the variable, which could lead to incorrect results.
- Lock-free: The atomic package uses lock-free algorithms to update the variables. This means that the operations are not blocked by locks, which can lead to contention and performance issues in concurrent programs.
- Atomic operations: The atomic package provides atomic operations that are designed to be executed atomically. This means that the operations are executed as a single, uninterruptible unit, which ensures that the variables are updated correctly even in the presence of concurrent access.
- Synchronization: The atomic package provides synchronization primitives, such as CompareAndSwap, that are designed to be used in concurrent programs. These primitives provide a way to synchronize access to shared variables, which ensures that the variables are updated correctly even in the presence of concurrent access.