go的CompareAndSwap返回false是什么意思?

huangapple go评论83阅读模式
英文:

What does it mean for go's CompareAndSwap to return false?

问题

在Go的源代码中有许多原子操作。例如,sync.Map使用了大量的原子操作,比如CompareAndSwapCompareAndSwap返回一个bool类型的值,表示操作是否成功。如果成功,它返回true,否则返回false。我对这个方法有一些疑问:

  1. 如果比较的值不相等,CompareAndSwap会返回false吗?
  2. 如果比较的值相等,CompareAndSwap会失败吗?
英文:

There are many atomic operations in the source code of go. For example, sync.Map uses a large number of atomic operations, such as CompareAndSwap, and CompareAndSwap returns a bool type value indicating whether it is successful. If successful, it returns true, otherwise it returns false. I have some doubts about this method:

  1. Does CompareAndSwap return false if the values of compare are not equal?
  2. Will CompareAndSwap fail if the compared values are equal?

答案1

得分: 2

根据文档所述,CompareAndSwap的等效操作如下:

if *addr == old {
	*addr = new
	return true
}
return false

因此,如果值不相等,交换操作将不会发生,它会返回false。这对于判断某个值是否自上次设置以来发生了变化,并在未发生变化时将其设置为其他值非常有用。

英文:

As the documentation states, CompareAndSwap is equivalent to:

if *addr == old {
	*addr = new
	return true
}
return false

So it returns false if the values are not equal, and the swap operation did not take place. This is useful to figure out if some value has changed since the last time it was set, and it if hasn't changed, set it to something else.

huangapple
  • 本文由 发表于 2023年1月15日 09:30:04
  • 转载请务必保留本文链接:https://go.coder-hub.com/75122412.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定