atomic.CompareAndSwapUint64() Function in Golang With Examples
In Go language, atomic packages supply lower-level atomic memory that is helpful is implementing synchronization algorithms. The CompareAndSwapUint64() function in Go language is used to perform the compare and swap operation for an uint64 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 CompareAndSwapUint64(addr *uint64, old, new uint64) (swapped bool)
Here, addr indicates address, old indicates uint64 value that is old one, and new is the uint64 new value that will swap itself from the old value.
Note: (*uint64) is the pointer to a uint64 value. And uint64 is integer type of bit size 64. Moreover, int64 contains the set of all unsigned 64-bit integers ranging from 0 to 18446744073709551615.
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 uint64 = 34764576575
)
Swap := atomic.CompareAndSwapUint64(&i, 34764576575, 575765878)
fmt.Println(Swap)
fmt.Println( "The new value of i is: " ,i)
}
|
Output:
true
The new value of i is: 575765878
Example 2:
package main
import (
"fmt"
"sync/atomic"
)
func main() {
var (
i uint64 = 143255757
)
var oldvalue = atomic.SwapUint64(&i, 4676778904)
fmt.Println( "Swapped_value:" , i, ", old_value:" , oldvalue)
Swap := atomic.CompareAndSwapUint64(&i, 143255757, 9867757)
fmt.Println(Swap)
fmt.Println( "The value of i is: " ,i)
}
|
Output:
Swapped_value: 4676778904 , old_value: 143255757
false
The value of i is: 4676778904
Here, the swapped value obtained from the swapping operation must be the old value. i.e. 4676778904 that’s why false is returned.
Last Updated :
01 Apr, 2020
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...