In Go language, atomic packages supply lower-level atomic memory that is helpful is implementing synchronization algorithms. The CompareAndSwapUintptr() function in Go language is used to perform the compare and swap operation for an uintptr 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 CompareAndSwapUintptr(addr *uintptr, old, new uintptr) (swapped bool)
Here, addr indicates address, old indicates uintptr value that is old one, and new is the uintptr new value that will swap itself from the old value is stored at addr.
Note: (*uintptr) is the pointer to a uintptr value. And uintptr is an unsigned integer type that is too large and contains a bit pattern of any pointer.
Return Value: It returns true if swapping is accomplished else it returns false.
Example 1:
// Program to illustrate the usage of // CompareAndSwapUintptr function in Golang // Including main package package main // importing fmt and sync/atomic import ( "fmt"
"sync/atomic"
) // Main function func main() { // Assigning variable
// values to the uintptr
var (
i uintptr = 34764686
j uintptr = 41343432525245
k uintptr = 0
)
// Calling CompareAndSwapUintptr
// method with its parameters
Swap1 := atomic.CompareAndSwapUintptr(&i,
34764686, 647567565)
Swap2 := atomic.CompareAndSwapUintptr(&j,
41343432525245, 76)
Swap3 := atomic.CompareAndSwapUintptr(&k,
0, 15)
// Displays true if
// swapped else false
fmt.Println(Swap1)
fmt.Println(Swap2)
fmt.Println(Swap3)
// Prints addr
fmt.Println(i)
fmt.Println(j)
fmt.Println(k)
} |
Output:
true true true 647567565 76 15
Example 2:
// Program to illustrate the usage of // CompareAndSwapUintptr function in Golang // Including main package package main // Importing fmt and sync/atomic import ( "fmt"
"sync/atomic"
) // Main function func main() { // Assigning variable
// values to the uintptr
var (
x uintptr = 56466244
)
// Swapping operation
var oldvalue = atomic.SwapUintptr(&x, 2344444)
// Printing old value
// and swapped value
fmt.Println( "Swapped_value:" , x,
", old_value:" , oldvalue)
// Calling CompareAndSwapUintptr
// method with its parameters
Swap := atomic.CompareAndSwapUintptr(&x,
56466244, 13232324)
// Displays true if
// swapped else false
fmt.Println(Swap)
fmt.Println(x)
} |
Output:
Swapped_value: 2344444, old_value: 56466244 false 2344444
Here, the swapped value obtained from the swapping operation must be the old value of the CompareAndSwapUintptr() method but here the old value taken is the old value of swapping operation which is not correct that’s why false is returned.