3 ms·
You can do better than CAS for spinlocks on bits. The representation needs to handle locked, unlocked, try-lock. Let unlocked be 0 and locked be 1. So try-lock
by JonChesterfield 4y ago
You can do better than CAS for spinlocks on bits. The representation needs to handle locked, unlocked, try-lock. Let unlocked be 0 and locked be 1. So try-lock can be done with a compare and swap with one bit set and the rest a guess at the remainder of the word, then loop.
Instead of that, use fetch_or with only the corresponding bit set. That leaves the rest of the word unchanged and the locking position set to one.
Then check the return value. You know the lock is taken now. If the bit is set in the return, it was locked before your fetch_or. So try-lock failed and changed nothing. If the bit is clear in the return, try-lock succeeded and you now hold the lock.
This eliminates the guess the word part of using CAS and eliminates the retry loop you get because other bits in the word might have changed while you were trying to lock it.