atomic.CompareAndSwapUintptr() Function in Golang With Examples
Last Updated :
01 Apr, 2020
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:
package main
import (
"fmt"
"sync/atomic"
)
func main() {
var (
i uintptr = 34764686
j uintptr = 41343432525245
k uintptr = 0
)
Swap1 := atomic.CompareAndSwapUintptr(&i,
34764686, 647567565)
Swap2 := atomic.CompareAndSwapUintptr(&j,
41343432525245, 76)
Swap3 := atomic.CompareAndSwapUintptr(&k,
0, 15)
fmt.Println(Swap1)
fmt.Println(Swap2)
fmt.Println(Swap3)
fmt.Println(i)
fmt.Println(j)
fmt.Println(k)
}
|
Output:
true
true
true
647567565
76
15
Example 2:
package main
import (
"fmt"
"sync/atomic"
)
func main() {
var (
x uintptr = 56466244
)
var oldvalue = atomic.SwapUintptr(&x, 2344444)
fmt.Println( "Swapped_value:" , x,
", old_value:" , oldvalue)
Swap := atomic.CompareAndSwapUintptr(&x,
56466244, 13232324)
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.
Share your thoughts in the comments
Please Login to comment...