3 ms·
The 'lock' variable is shared among threads. Compare is needed to avoid stomping on the lock acquired by another thread.
by ww520 5y ago
The 'lock' variable is shared among threads. Compare is needed to avoid stomping on the lock acquired by another thread.
- dragontamer 5y agoNo it isn't. 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.
- ww520 5y agoYou are right. XCHG can do the job to acquire the lock. At least on x86, XCHG does lock the cache line on the address of the variable, so it should be ok.