更强大的原子指令

Compare and exchange (“test and set”)

  • (lock) cmpxchg SRC, DEST
TEMP = DEST
if accumulator == TEMP:
    ZF = 1
    DEST = SRC
else:
    ZF = 0
    accumulator = TEMP
  • 🤔 看起来没复杂多少,好像又复杂了很多
    • 学编程/操作系统 “纸面理解” 是不行的
    • 一定要写代码加深印象
      • 对于这个例子:我们可以列出 “真值表”

在自旋锁中代替 xchg

在自旋锁的实现中,xchg 完全可以用 cmpxchg 代替

// cmpxchg(old='🔑', new='🛑', *ptr)
int tmp = *ptr;
if (tmp == '🔑') {
  *ptr = '🛑'
  assert(tmp == '🔑');
} else {
  assert(tmp == '🛑');
}
return tmp;
  • 这么做有什么好处吗?
    • 有的,在自旋失败的时候减少了一次 store
    • 当然,现代处理器也可以优化 xchg

多出的 Compare: 用处

同时检查上一次获得的值是否仍然有效 + 修改生效

// Create a new node
retry:
  expected = head;
  node->next = expected;
  seen = cmpxchg(expected, node, &head);
  if (seen != expected)
    goto retry;

习题:如何实现 pop()