











原文: http://www.manongjc.com/detail/30-anadyrrwgsoebxp.html
--------------
在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"
)
输出:
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"
)
输出:
Swapped:56677, old value:686788787 false 56677
在这里,CompareAndSwapInt64方法中的旧值必须是SwapInt64方法返回的交换值。此处不执行交换,因此返回false。
此内容由惯性聚合(RSS阅读器)自动聚合整理,仅供阅读参考。 原文来自 — 版权归原作者所有。