自旋锁的代码实现

自旋锁代码的逻辑结构如下所示:

int table = YES;
//假定xchg的操作是原子的
int xchg(int *table, int new) {
    // wait for implementation
}

void lock() {
retry:
  int got = xchg(&table, NOPE);
  if (got == NOPE)
    goto retry;
  assert(got == YES);
}

void unlock() {
  xchg(&table, YES);  // 为什么不是 table = YES; ?
}
解读
  • xchg 的硬件实现有很多种,这只是其中的一种,叫做 test and set,还有 compare and swapLoad-linked And Store-conditionalfetch and add 等实现方法,这里就不多赘述了;
  • 使用 xchg(&table, YES) 而非直接赋值 table = YES,主要是为了保持操作的原子性。xchg 操作通常是原子的,这意味着在多线程环境中,xchg 操作可以确保在读取和写入过程中不会被其他线程中断。

xchg 的实现: