In Go language, atomic packages supply lower-level atomic memory that is helpful is implementing synchronization algorithms. The CompareAndSwapPointer() function in Go language is used to perform the compare and swap operation for a unsafe.Pointer value. This function is defined under the atomic package. Here, you need to import “sync/atomic” package in order to use these functions.
Syntax:
func CompareAndSwapPointer(addr *unsafe.Pointer, old, new unsafe.Pointer) (swapped bool)
Here, addr indicates address, old indicates unsafe.Pointer value that is the old swapped value which is returned from the SwapPointer operation, and new is the unsafe.Pointer new value that will swap itself from the old swapped value.
Note: (*unsafe.Pointer) is the pointer to a unsafe.Pointer value. And unsafe.Pointer type is helpful in enabling transitions between arbitrary types and builtin uintptr type. Moreover, unsafe is a package that is helpful in type safety of Go programs.
Return Value: It returns true if swapping is accomplished else it returns false.
Example 1:
// Program to illustrate the usage of // CompareAndSwapPointer function in Golang // Including main package package main // Importing fmt, // sync/atomic and unsafe import ( "fmt"
"sync/atomic"
"unsafe"
) // Defining a struct type P type P struct { x, y, z int }
// Declaring pointer // to P struct type var pP *P // Main function func main() { // Defining addr unsafe.Pointer
var unsafe1 = (*unsafe.Pointer)(unsafe.Pointer(&pP))
// Old unsafe pointer
var sy P
// Defining new unasfe.pointer
px := atomic.SwapPointer(
unsafe1, unsafe.Pointer(&sy))
// Calling CompareAndSwapPointer
// method with its parameters
y := atomic.CompareAndSwapPointer(
unsafe1, unsafe.Pointer(&sy), px)
// Returns true if
// swapped else false
fmt.Println(y)
} |
Output:
true
Example 2:
// Program to illustrate the usage of // CompareAndSwapPointer function in Golang // Including main package package main // importing fmt, // sync/atomic and unsafe import ( "fmt"
"sync/atomic"
"unsafe"
) // Defining a struct type P type P struct { x, y, z int }
// Declaring pointer to P struct type var pP *P // Main function func main() { // Defining addr unsafe.Pointer
var unsafe1 = (*unsafe.Pointer)(unsafe.Pointer(&pP))
// Old unsafe pointer
var sy P
// Defining new unasfe.pointer
px := atomic.SwapPointer(
unsafe1, unsafe.Pointer(&sy))
// Calling CompareAndSwapPointer
// method with its parameters
y := atomic.CompareAndSwapPointer(
unsafe1, px, unsafe.Pointer(&sy))
// Returns true if
// swapped else false
fmt.Println(y)
} |
Output:
false
In the above example, Swapping is not performed as the old value here in the CompareAndSwapPointer() method must be the value returned from the SwapPointer() method but here old value is different so false is returned from the above code.