atomic.CompareAndSwapInt32() 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 CompareAndSwapInt32() function in Go language is used to perform the compare and swap operation for an int32 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 CompareAndSwapInt32(addr *int32, old, new int32) (swapped bool)
Here, addr indicates address, old indicates int32 value that is the old swapped value which is returned from the swapped operation, and new is the int32 new value that will swap itself from the old swapped value.
Note: (*int32) is the pointer to a int32 value. And int32 is integer type of bit size 32. Moreover, int32 contains the set of all signed 32-bit integers from -2147483648 to 2147483647.
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 int32 = 111
)
var old_value = atomic.SwapInt32(&i, 498)
fmt.Println( "Swapped:" , i, ", old value:" , old_value)
Swap := atomic.CompareAndSwapInt32(&i, 498, 675)
fmt.Println(Swap)
fmt.Println( "The Value of i is: " ,i)
}
|
Output:
Swapped: 498 , old value: 111
true
The Value of i is: 675
Example 2:
package main
import (
"fmt"
"sync/atomic"
)
func main() {
var (
i int32 = 111
)
var old_value = atomic.SwapInt32(&i, 498)
fmt.Println( "Swapped:" , i, ", old value:" , old_value)
Swap := atomic.CompareAndSwapInt32(&i, 111, 675)
fmt.Println(Swap)
fmt.Println( "The Value of i is: " ,i)
}
|
Output:
Swapped: 498 , old value: 111
false
The Value of i is: 498
Here, the old value in the CompareAndSwapInt32 method must be the swapped value returned from the SwapInt32 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...