atomic.CompareAndSwapInt64() 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 CompareAndSwapInt64() function in Go language is used to perform the compare and swap operation for an int64 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 CompareAndSwapInt64(addr *int64, old, new int64) (swapped bool)
Here, addr indicates address, old indicates int64 value that is the old swapped value which is returned from the swapped operation, and new is the int64 new value that will swap itself from the old swapped value.
Note: (*int64) is the pointer to a int64 value. And int64 is integer type of bit size 64. Moreover, int64 contains the set of all signed 64-bit integers from -9223372036854775808 to 9223372036854775807.
Return Value: It returns true if swapping is accomplished else it returns false.
Below examples illustrates the use of the above method:
Example 1:
package main
import (
"fmt"
"sync/atomic"
)
func main() {
var (
i int64 = 686788787
)
var old_value = atomic.SwapInt64(&i, 56677)
fmt.Println( "Swapped:" , i, ", old value:" , old_value)
Swap := atomic.CompareAndSwapInt64(&i, 56677, 908998)
fmt.Println(Swap)
fmt.Println( "The Value of i is: " ,i)
}
|
Output:
Swapped: 56677 , old value: 686788787
true
The Value of i is: 908998
Example 2:
package main
import (
"fmt"
"sync/atomic"
)
func main() {
var (
i int64 = 686788787
)
var old_value = atomic.SwapInt64(&i, 56677)
fmt.Println( "Swapped:" , i, ", old value:" , old_value)
Swap := atomic.CompareAndSwapInt64(&i, 686788787, 908998)
fmt.Println(Swap)
fmt.Println(i)
}
|
Output:
Swapped: 56677, old value: 686788787
false
56677
Here, the old value in the CompareAndSwapInt64 method must be the swapped value returned from the SwapInt64 method. And here the swapping is not performed so false is returned.
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...