Skip to content
Related Articles

Related Articles

Improve Article
atomic.CompareAndSwapUint32() 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 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:




// Golang Program to illustrate the usage of
// CompareAndSwapUint32 function
  
// Including main package
package main
  
// importing fmt and sync/atomic
import (
    "fmt"
    "sync/atomic"
)
  
// Main function
func main() {
  
    // Assigning variable values to the uint32
    var (
        i uint32 = 34764
    )
  
    // Calling CompareAndSwapUint32 
    // method with its parameters
    Swap := atomic.CompareAndSwapUint32(&i, 34764, 67576)
  
    // Displays true if swapped else false
    fmt.Println(Swap)
    fmt.Println("The value of i is: ",i)
}

Output:

true
The value of i is:  67576

Example 2:




// Golang Program to illustrate the usage of
// CompareAndSwapUint32 function
  
// Including main package
package main
  
// importing fmt and sync/atomic
import (
    "fmt"
    "sync/atomic"
)
  
// Main function
func main() {
  
    // Assigning variable values to the uint32
    var (
        i uint32 = 54325
    )
  
    // Swapping operation
    var oldvalue = atomic.SwapUint32(&i, 7687)
  
    // Printing old value and swapped value
    fmt.Println("Swapped_value:", i, ", old_value:", oldvalue)
  
    // Calling CompareAndSwapUint32 method with its parameters
    Swap := atomic.CompareAndSwapUint32(&i, 54325, 677876)
  
    // Displays true if swapped else false
    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.




My Personal Notes arrow_drop_up
Recommended Articles
Page :