Home > Software engineering >  What does it mean for go's CompareAndSwap to return false?
What does it mean for go's CompareAndSwap to return false?

Time:01-15

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?

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.

  •  Tags:  
  • go
  • Related