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?
CodePudding user response:
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.