Compare and exchange (“test and set”)
TEMP = DEST
if accumulator == TEMP:
ZF = 1
DEST = SRC
else:
ZF = 0
accumulator = TEMP
在自旋锁的实现中,xchg 完全可以用 cmpxchg 代替
// cmpxchg(old='🔑', new='🛑', *ptr)
int tmp = *ptr;
if (tmp == '🔑') {
*ptr = '🛑'
assert(tmp == '🔑');
} else {
assert(tmp == '🛑');
}
return tmp;
同时检查
// Create a new node
retry:
expected = head;
node->next = expected;
seen = cmpxchg(expected, node, &head);
if (seen != expected)
goto retry;
习题:如何实现 pop()
?