自旋锁的代码实现
自旋锁代码的逻辑结构如下所示:
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 swap、Load-linked And Store-conditional、fetch and add等实现方法,这里就不多赘述了;- 使用
xchg(&table, YES)而非直接赋值table = YES,主要是为了保持操作的原子性。xchg操作通常是原子的,这意味着在多线程环境中,xchg操作可以确保在读取和写入过程中不会被其他线程中断。
xchg 的实现: