atomic.CompareAndSwapUint32() Function in Golang With Examples
In Go language, atomic packages supply lower-level atomic memory that is helpful is implementing synchronization algorithms. The CompareAndSwapUint32() function in Go language is used to perform the compare and swap operation for an uint32 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 CompareAndSwapUint32(addr *uint32, old, new uint32) (swapped bool)
Here, addr indicates address, old indicates uint32 value that is old one, and new is the uint32 new value that will swap itself from the old value.
Note: (*uint32) is the pointer to a uint32 value. And uint32 is integer type of bit size 32. Moreover, int32 contains the set of all unsigned 32-bit integers ranging from 0 to 4294967295.
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 uint32 = 34764
)
Swap := atomic.CompareAndSwapUint32(&i, 34764, 67576)
fmt.Println(Swap)
fmt.Println( "The value of i is: " ,i)
}
|
Output:
true
The value of i is: 67576
Example 2:
package main
import (
"fmt"
"sync/atomic"
)
func main() {
var (
i uint32 = 54325
)
var oldvalue = atomic.SwapUint32(&i, 7687)
fmt.Println( "Swapped_value:" , i, ", old_value:" , oldvalue)
Swap := atomic.CompareAndSwapUint32(&i, 54325, 677876)
fmt.Println(Swap)
fmt.Println( "The value of i is: " ,i)
}
|
Output:
Swapped_value: 7687 , old_value: 54325
false
The value of i is: 7687
Here, the swapped value obtained from the swapping operation must be the old value 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...