Open In App

atomic.CompareAndSwapInt32() Function in Golang With Examples

Last Updated : 01 Apr, 2020
Improve
Improve
Like Article
Like
Save
Share
Report

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:




// Golang Program to illustrate the usage of
// CompareAndSwapInt32 function
  
// Including main package
package main
  
// importing fmt and sync/atomic
import (
    "fmt"
    "sync/atomic"
)
  
// Main function
func main() {
  
    // Assigning variable values to the int32
    var (
        i int32 = 111
    )
  
    // Swapping
    var old_value = atomic.SwapInt32(&i, 498)
  
    // Printing old value and swapped value
    fmt.Println("Swapped:", i, ", old value:", old_value)
  
    // Calling CompareAndSwapInt32 method with its parameters
    Swap := atomic.CompareAndSwapInt32(&i, 498, 675)
  
    // Displays true if swapped else false
    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:




// Golang Program to illustrate the usage of
// CompareAndSwapInt32 function
  
// Including main package
package main
  
// importing fmt and sync/atomic
import (
    "fmt"
    "sync/atomic"
)
  
// Main function
func main() {
  
    // Assigning variable values to the int32
    var (
        i int32 = 111
    )
  
    // Swapping
    var old_value = atomic.SwapInt32(&i, 498)
  
    // Printing old value and swapped value
    fmt.Println("Swapped:", i, ", old value:", old_value)
  
    // Calling CompareAndSwapInt32
    // method with its parameters
    Swap := atomic.CompareAndSwapInt32(&i, 111, 675)
  
    // Displays true if
    // swapped else false
    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

Similar Reads