int lock = 0; void AcquireLock(int *lock){ while (ATOMIC_SWAP(lock, 1)){ sleep(10); //or futex or w/e } } void ReleaseLock(int *lock){ ATOMIC_SWAP(lock, 0); }
If lock = 1, you set the lock to 1 (aka do nothing).
If the lock is 0, you know it is unlocked and know you succeeded in acquiring the lock.
If many threads try to atomic swap, only one of them gets the zero.
------
The real issue here is the subtle memory barrier bug in that code.