英文:
What does it mean for go's CompareAndSwap to return false?
问题
在Go的源代码中有许多原子操作。例如,sync.Map
使用了大量的原子操作,比如CompareAndSwap
,CompareAndSwap
返回一个bool
类型的值,表示操作是否成功。如果成功,它返回true,否则返回false。我对这个方法有一些疑问:
- 如果比较的值不相等,
CompareAndSwap
会返回false吗? - 如果比较的值相等,
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:
- Does
CompareAndSwap
return false if the values of compare are not equal? - 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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论