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.
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.
Swapped: 498 , old value: 111 true The Value of i is: 675
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.