Golang atomic.CompareAndSwapInt64()实例讲解

时间:2022-04-07
本文章向大家介绍Golang atomic.CompareAndSwapInt64()实例讲解,主要分析其语法、参数、返回值和注意事项,并结合实例形式分析了其使用技巧,希望通过本文能帮助到大家理解应用这部分内容。

在Go语言中,原子包提供lower-level原子内存,这对实现同步算法很有帮助。 Go语言中的CompareAndSwapInt64()函数用于对int64值执行比较和交换操作。此函数在原子包下定义。在这里,您需要导入“sync/atomic”软件包才能使用这些函数。

用法:

func CompareAndSwapInt64(addr *int64, old, new int64) (swapped bool)

在这里,addr表示地址,old表示int64值,它是从交换操作返回的旧交换值,而new则是int64新值,它将与旧交换值进行交换。

注意:(* int64)是指向int64值的指针。并且int64是位大小64的整数类型。此外,int64包含从-9223372036854775808到9223372036854775807的所有带符号的64位整数的集合。

返回值:如果交换完成,则返回true,否则返回false。



以下示例说明了上述方法的用法:

范例1:

// Golang Program to illustrate the usage of 
// CompareAndSwapInt64 function 
  
// Including main package 
package main 
  
// importing fmt and sync/atomic 
import ( 
    "fmt"
    "sync/atomic"
) 
  
// Main function 
func main() { 
  
    // Assigning variable values to the int64 
    var ( 
        i int64 = 686788787 
    ) 
  
    // Swapping 
    var old_value = atomic.SwapInt64(&i, 56677) 
  
    // Printing old value and swapped value 
    fmt.Println("Swapped:", i, ", old value:", old_value) 
  
    // Calling CompareAndSwapInt64  
    // method with its parameters 
    Swap:= atomic.CompareAndSwapInt64(&i, 56677, 908998) 
  
    // Displays true if swapped else false 
    fmt.Println(Swap) 
    fmt.Println("The Value of i is:",i) 
}

输出:

Swapped:56677 , old value:686788787
true
The Value of i is: 908998

范例2:

// Golang Program to illustrate the usage of 
// CompareAndSwapInt64 function 
  
// Including main package 
package main 
  
// importing fmt and sync/atomic 
import ( 
    "fmt"
    "sync/atomic"
) 
  
// Main function 
func main() { 
  
    // Assigning variable values to the int64 
    var ( 
        i int64 = 686788787 
    ) 
  
    // Swapping 
    var old_value = atomic.SwapInt64(&i, 56677) 
  
    // Printing old value and swapped value 
    fmt.Println("Swapped:", i, ", old value:", old_value) 
  
    // Calling CompareAndSwapInt64  
    // method with its parameters 
    Swap:= atomic.CompareAndSwapInt64(&i, 686788787, 908998) 
  
    // Displays true if swapped else false 
    fmt.Println(Swap) 
    fmt.Println(i) 
}

输出:

Swapped:56677, old value:686788787
false
56677

在这里,CompareAndSwapInt64方法中的旧值必须是SwapInt64方法返回的交换值。此处不执行交换,因此返回false。