Compare and swap
Any time you test for a condition and act based on the result, you can create a race condition. For example, the following function does not prevent mutual exclusion, despite the use of atomics:
var locked sync.Bool func wrongCriticalSectionExample() { if !locked.Load() { // Another goroutine may lock it now! locked.Store(true) defer locked.Store(false) // This goroutine enters critical section // but so can another goroutine } }
The function starts by testing whether the atomic locked
value is false
. Two goroutines can execute this statement simultaneously, and seeing that it is false
, both can enter the...