目前我们看到,为了构建更有效率的锁,一个操作系统提供的一种支持。其他操作系统也提供了类似的支持,但细节不同。
例如,Linux 提供了futex,它类似于Solaris 的接口,但提供了更多内核功能。具体来说,每个futex 都关联一个特定的物理内存位置,也有一个事先建好的内核队列。调用者通过futex 调用(见下面的描述)来睡眠或者唤醒。
具体来说,有两个调用。调用futex_wait(address, expected)时,如果address 处的值等于expected,就会让调线程睡眠。否则,调用立刻返回。调用futex_wake(address)唤醒等待队列中的一个线程。图28.9 是Linux 环境下的例子。
void mutex_lock (int *mutex) {
int v;
/* Bit 31 was clear, we got the mutex (this is the fastpath) */
if (atomic_bit_test_set (mutex, 31) == 0)
return;
atomic_increment (mutex);
while (1) {
if (atomic_bit_test_set (mutex, 31) == 0) {
atomic_decrement (mutex);
return;
}
/* We have to wait now. First make sure the futex value
we are monitoring is truly negative (i.e. locked). */
v = *mutex;
if (v >= 0)
continue;
futex_wait (mutex, v);
}
}
void mutex_unlock (int *mutex) {
/* Adding 0x80000000 to the counter results in 0 if and only if
there are not other interested threads */
if (atomic_add_zero (mutex, 0x80000000))
return;
/* There are other threads waiting for this mutex,
wake one of them up. */
futex_wake (mutex);
图28.9 基于Linux 的futex 锁
这段代码来自nptl 库(gnu libc 库的一部分)[L09]中lowlevellock.h,它很有趣。基本上,它利用一个整数,同时记录锁是否被持有(整数的最高位),以及等待者的个数(整数的其余所有位)。因此,如果锁是负的,它就被持有(因为最高位被设置,该位决定了整数的符号)。这段代码的有趣之处还在于,它展示了如何优化常见的情况,即没有竞争时:只有一个线程获取和释放锁,所做的工作很少(获取锁时测试和设置的原子位运算,释放锁时原子的加法)。你可以看看这个“真实世界”的锁的其余部分,是否能理解其工作原理。