📌  相关文章
📜  Golang 中的 atomic.CompareAndSwapUint64()函数示例

📅  最后修改于: 2021-10-24 13:06:49             🧑  作者: Mango

在 Go 语言中,原子包提供较低级别的原子内存,这有助于实现同步算法。 Go语言的CompareAndSwapUint64()函数用于对uint64值进行比较和交换操作。这个函数是在 atomic 包下定义的。在这里,您需要导入“sync/atomic”包才能使用这些功能。

句法:

func CompareAndSwapUint64(addr *uint64, old, new uint64) (swapped bool)

这里, addr表示地址, old表示旧值的 uint64 值, new是将从旧值交换自身的 uint64 新值。

注意: (*uint64) 是指向 uint64 值的指针。 uint64 是位长为 64 的整数类型。此外,int64 包含从 0 到 18446744073709551615 的所有无符号 64 位整数的集合。

返回值:如果交换完成则返回真,否则返回假。

示例 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)
}

输出:

true
The new value of i is:  575765878

示例 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)
}

输出:

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

这里,交换操作得到的交换值必须是旧值。即 4676778904 这就是返回 false 的原因。