Skip to content
Related Articles

Related Articles

Improve Article
atomic.CompareAndSwapUint64() 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 CompareAndSwapUint64() function in Go language is used to perform the compare and swap operation for an uint64 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 CompareAndSwapUint64(addr *uint64, old, new uint64) (swapped bool)

Here, addr indicates address, old indicates uint64 value that is old one, and new is the uint64 new value that will swap itself from the old value.

Note: (*uint64) is the pointer to a uint64 value. And uint64 is integer type of bit size 64. Moreover, int64 contains the set of all unsigned 64-bit integers ranging from 0 to 18446744073709551615.

Return Value: It returns true if swapping is accomplished else it returns false.



Example 1:




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

Output:

true
The new value of i is:  575765878

Example 2:




// Golang Program to illustrate the usage of
// CompareAndSwapUint64 function
  
// Including main package
package main
  
// importing fmt and sync/atomic
import (
    "fmt"
    "sync/atomic"
)
  
// Main function
func main() {
  
    // Assigning variable 
    // values to the uint64
    var (
        i uint64 = 143255757
    )
  
    // Swapping operation. Here value of i become
    // 4676778904
    var oldvalue = atomic.SwapUint64(&i, 4676778904)
  
    // Printing old value and swapped value
    fmt.Println("Swapped_value:", i, ", old_value:", oldvalue)
  
    // Calling CompareAndSwapUint64 
    // method with its parameters
    Swap := atomic.CompareAndSwapUint64(&i, 143255757, 9867757)
  
    // Displays true if swapped else false
    fmt.Println(Swap)
    fmt.Println("The value of i is: ",i)
}

Output:

Swapped_value: 4676778904 , old_value: 143255757
false
The value of i is:  4676778904

Here, the swapped value obtained from the swapping operation must be the old value. i.e. 4676778904 that’s why false is returned.




My Personal Notes arrow_drop_up
Recommended Articles
Page :