OSTEP:Locks
OSTEP:Locks
本篇对应 OSTEP Version 1.10 的 “Locks”。lock 将 critical section 保护成类似 single atomic instruction 的区域;本篇从失败的简单方案推进到 hardware atomic primitive 与 OS support。
类型与定位
- 笔记类型:深度分析
- 翻译基准:官方
threads-locks.pdf,Version 1.10。 - 图件说明:原文的 lock code、hardware primitive、spin 与 queue 图按原位置保留为代码块或 Mermaid;没有独立 raster image。
TL;DR
- lock 有两个基本状态:available 和 held,最多一个 thread 持有它。
- 好的 lock 至少要满足 mutual exclusion,并在 fairness、低 contention cost 和高 contention scalability 上表现良好。
- 禁用 interrupts 只适合受信任的 kernel/single-CPU 局部场景,不能作为通用 multiprocessor 方案。
- 普通 load/store 无法原子地完成 test-and-set;需要 hardware atomic instruction,如
xchg、compare-and-swap、fetch-and-add。 - spin lock 在短等待上简单有效,但会浪费 CPU;OS park/unpark 可让长时间等待的 thread 睡眠。
目录
| 章节 | 内容 |
|---|---|
| Lock 的基本思想 | acquire/release 与 mutual exclusion |
| 如何评价 lock | correctness、fairness、performance |
| 禁用 interrupts | single-CPU 的早期方案 |
| 简单 flag 为什么失败 | test-and-set race |
| Hardware atomic instructions | x86 与通用 primitives |
| Spin lock 与 OS support | 自旋、阻塞与唤醒 |
| 锁粒度 | coarse-grained 与 fine-grained |
Lock 的基本思想
lock_t mutex;
lock(&mutex);
balance = balance + 1; // critical section
unlock(&mutex);
lock 变量保存当前状态:available/unlocked/free,或 acquired/locked/held。若一个 thread 已持有 lock,其他调用 lock() 的 threads 必须等待;owner 调用 unlock() 后,某个等待者才能进入 critical section。
lock 将部分 scheduling control 交还给 programmer:OS 仍决定 thread 何时运行,但 programmer 可以保证受保护的代码不会被多个 threads 同时执行。
如何评价 lock
- Correctness / mutual exclusion:是否真的阻止多个 threads 同时进入 critical section?
- Fairness:等待的 thread 是否有公平机会获得 lock,是否可能 starvation?
- Performance:无 contention、单 CPU contention、多 CPU contention 下,acquire/release 和等待的成本是多少?
一个只保证正确性但导致严重 starvation 的 lock,或在高 contention 下让所有 CPU 浪费在等待上的 lock,都不是完整的工程答案。
这三个维度不能互相替代:一个 lock 即使 benchmark 很快,如果不能保证 mutual exclusion,就不是正确的 lock;一个正确的 lock 如果让某个 thread 无限期等待,也可能无法满足实际系统的 fairness 要求。评估 spin lock 时还要区分 single CPU 和 multiprocessor:前者的等待者会独占 CPU,后者则可能在 owner 运行于另一颗 CPU 时有效地等待。
禁用 interrupts
早期 single-processor 系统可以这样保护 critical section:
void lock() {
DisableInterrupts();
}
void unlock() {
EnableInterrupts();
}
single CPU 上,禁用 interrupts 后不会发生 timer interrupt 或其他异步切换,代码看起来像 atomic 执行。但问题明显:
- 需要允许调用者执行 privileged operation,恶意或错误程序可以永久关闭 interrupts;
- multiprocessor 上其他 CPU 仍可进入同一个 critical section;
- 长时间屏蔽 interrupts 可能丢失 device completion 等事件。
因此它只适合 OS 内部非常受控的短临界区,不能作为通用 user-level lock。
简单 flag 为什么失败
typedef struct __lock_t {
int flag; // 0: available, 1: held
} lock_t;
void lock(lock_t *mutex) {
while (mutex->flag == 1)
; // spin
mutex->flag = 1;
}
上述代码将“检查 flag”和“设置 flag”分成两个普通 memory operations。两个 threads 可能同时读到 0,然后都写入 1,最终同时认为自己获得了 lock。问题不在 flag 的表示,而在 test-and-set 没有作为一个不可分割的 atomic operation 执行。
Hardware atomic instructions
hardware 提供的 atomic read-modify-write primitive 可以把检查与更新绑定起来:
int TestAndSet(int *old_ptr, int new) {
int old = *old_ptr;
*old_ptr = new;
return old;
}
void lock(lock_t *mutex) {
while (TestAndSet(&mutex->flag, 1) == 1)
;
}
void unlock(lock_t *mutex) {
mutex->flag = 0;
}
常见 primitives 包括:
| primitive | 用途 |
|---|---|
test-and-set / xchg | 原子地读取并设置 flag |
| compare-and-swap | 仅当旧值符合预期时写入新值 |
| fetch-and-add | 原子地增加 counter,可构造 ticket lock |
| load-linked/store-conditional | 某些 RISC 架构的条件更新 |
真实代码还需要正确的 memory ordering/fence,保证不同 CPU 看到的数据顺序符合同步协议。
TestAndSet 的关键不是其中两行 C 代码本身,而是硬件把整个 read-modify-write 当作一个 atomic operation。若 lock 当前为 0,调用返回旧值 0,同时把 flag 设为 1,于是该 thread 进入 critical section;其他 concurrent 调用只能读到旧值 1,并继续 spin。unlock 把 flag 写回 0 后,等待者中的某一个才可能成功。
另一类常用 primitive 是 compare-and-swap:只有当 memory 中的旧值等于期望值时,才写入新值并报告成功。fetch-and-add 则能原子地增加 counter,并据此构造按号码服务的 ticket lock。后者通常比简单 spin lock 更公平,但等待者仍可能在共享计数器上造成 cache-coherence traffic。
Spin lock 与 OS support
最简单的 atomic lock 在等待时持续 polling,称为 spin lock。若临界区很短、等待时间低,spin 可能比 context switch 更快;若 lock 被长时间持有,等待 thread 会浪费 CPU cycles。
更好的方案是让 lock library 与 OS 协作:竞争失败的 thread 进入 sleep/park,由 owner unlock 时 wake/unpark 一个等待者。这样长等待不会持续占用 CPU,但 sleep/wakeup 本身有系统调用和调度开销。
flowchart TD
A[尝试 acquire] --> B{atomic acquire 成功?}
B -->|yes| C[进入 critical section]
C --> D[release]
B -->|短等待| E[spin]
E --> A
B -->|长等待| F[park/sleep]
D --> G[wake waiter]
G --> A
lock implementation 的目标是根据 contention 和等待时长,在 spin 与 sleep 之间平衡。
锁粒度
- Coarse-grained locking:一个大 lock 保护很多 data,简单但限制并发。
- Fine-grained locking:不同 data structure 使用不同 locks,允许更多并发,但提高 deadlock、ordering 和维护复杂度。
flowchart LR
A[一个全局 lock] --> B[简单、竞争集中]
C[多个 data-specific locks] --> D[并行度更高]
C --> E[锁顺序与 deadlock 风险更高]
锁的正确性先于性能;只有在明确的共享数据边界和锁顺序之后,才适合进一步细化粒度。
源文档逐段补充
POSIX mutex 与 lock 的工程目标
POSIX 将 lock 称为 mutex(mutual exclusion)。不同的 mutex 可以保护不同的 variable 或 data structure;因此,使用多个 lock 往往比让所有 critical section 共用一个 global lock 有更好的 concurrency。lock 的实现目标不只是“能工作”,还包括低 uncontended cost、合理的 contention behavior 和可接受的 fairness。
构造 lock 时应明确回答三个问题:它是否始终保证 mutual exclusion;一个持续等待的 thread 是否可能 starvation;在无竞争、单 CPU 竞争和多 CPU 竞争下,acquire/release 的 overhead 分别是多少。特别是 single CPU 上的 spin lock,等待者占用的 CPU 会阻止 owner 运行;多 CPU 上 owner 可能在另一颗 CPU 运行,自旋才可能有意义。
为什么普通 load/store 不够
最初的 flag 方案有两个问题。正确性方面,两个 thread 可以先后检查到 flag == 0,然后都把它设置为 1,从而同时进入 critical section。性能方面,等待者一直执行空 loop;在 uniprocessor 上,owner 甚至无法获得 CPU 来执行 unlock。
可以把 scheduler 想象成一个主动寻找 bug 的 adversarial scheduler:它会在每一个最危险的 instruction boundary 发生 interrupt。并发代码只有在所有合法 interleaving 下都正确,才算真正正确;“测试运行时刚好没有切换到危险位置”不是证明。
Test-and-set 与 atomic exchange
int TestAndSet(int *old_ptr, int new) {
int old = *old_ptr;
*old_ptr = new;
return old;
}
这个 C 伪代码只有在 hardware 保证整个 read-modify-write atomic 时才成立。若 flag 原来是 0,第一个调用原子地得到 old value 0 并写入 1,于是获得 lock;并发调用只能得到 old value 1 并继续 spin。SPARC 将类似 primitive 称为 ldstub,x86 通常使用带 lock 语义的 atomic xchg。
没有 special hardware 时,Dekker 与 Peterson algorithm 曾尝试仅用 atomic load/store 构造 two-thread lock。Peterson 使用 flag[] 表示意图、turn 表示让谁先进入;但现代 hardware 的 relaxed memory-consistency model 使这类算法难以直接依赖,实际系统通常使用硬件提供的 atomic primitives。
Spin lock 的具体评价
test-and-set spin lock 简单、代码短,并且在 critical section 极短、owner 正在另一颗 CPU 上运行时可能优于 sleep/wakeup。代价是每次失败的 test-and-set 都会产生 shared memory/cache-coherence traffic;等待者越多,系统越可能把大量带宽耗在反复争抢同一 cache line 上。
还必须区分三种情况:
| 场景 | spin 的表现 |
|---|---|
| 无 contention | 只有一次 atomic operation,成本低 |
| 单 CPU 有 contention | waiter 占用唯一 CPU,可能让 owner 无法完成,表现很差 |
| 多 CPU 有 contention | owner 可在其他 CPU 上运行,短 critical section 时可能尚可,但 coherence traffic 会增加 |
仅有 mutual exclusion 也不等于 fairness。简单 test-and-set 不保证先等待的 thread 先获得 lock,某个 thread 可能长期抢不到,发生 starvation。
Compare-and-swap
compare-and-swap 只有在 memory 中的旧值等于 expected value 时才写入 new value,并报告成功与否:
int CompareAndSwap(int *ptr, int expected, int new) {
int actual = *ptr;
if (actual == expected)
*ptr = new;
return actual;
}
void lock(lock_t *lock) {
while (CompareAndSwap(&lock->flag, 0, 1) != 0)
;
}
相比 test-and-set,compare-and-swap 更通用,能在 lock-free data structure 等场景中根据状态条件更新 memory;但它仍可能需要大量 retry,并不能自动解决 fairness 或 contention scalability。
Load-linked / store-conditional
一些 RISC architecture 提供 load-linked(LL)和 store-conditional(SC)这一对 instruction。LL 读取一个 address 并建立 reservation;如果从 LL 到 SC 之间没有其他 thread/processor 对该 address 的冲突更新,SC 才成功写入,否则失败。lock 可以不断执行 LL、检查旧值、尝试 SC;失败时重新开始。这种机制把“期间是否被干扰”的检查交给 hardware。
Fetch-and-add 与 ticket lock
fetch-and-add 原子地返回旧值并增加 counter:
int FetchAndAdd(int *ptr) {
int old = *ptr;
*ptr = old + 1;
return old;
}
利用它可以构造 ticket lock:每个 waiter 原子地领取一个 ticket,只有 turn 等于自己的 ticket 时进入;unlock 时增加 turn。这样获得 lock 的顺序更接近 FIFO,fairness 通常优于简单 test-and-set,但所有 waiter 仍会观察共享 turn,在大量 CPU 上可能造成 coherence traffic。
从自旋到阻塞
硬件 lock 的代码短小,却可能在高 contention 下持续浪费 CPU。一个渐进方案是 yield():竞争失败的 thread 主动让出 CPU,避免完全 busy-wait;但如果 runnable queue 中没有真正能释放 lock 的 owner,反复 yield 仍会产生调度开销。
更完整的方案是使用 OS 提供的 park/unpark 或 sleep/wakeup:失败者进入 wait queue 并睡眠,unlock 时由 owner 唤醒一个 waiter。实现必须小心处理“刚检查完 lock、正准备睡眠时 owner 已 unlock”的 lost-wakeup race,因此 lock 状态检查、入队和睡眠需要由 OS primitive 以正确顺序完成。
lock():
fast path:atomic acquire 成功 → 立即返回
slow path:加入 wait queue → park/sleep
unlock():
释放 lock
若存在 waiter → unpark/wake 一个 waiter
Solaris 提供类似 park()/unpark() 的支持;Linux 提供 futex(fast userspace mutex),让 uncontended 情况留在 user space,只有竞争时才进入 kernel。不同 OS 的 primitive 名称不同,但共同目标是让常见的无竞争路径短,让长等待路径不占用 CPU。
优先级反转
spin 还有 priority inversion 风险:低优先级 thread 持有 lock 时,高优先级 thread 自旋等待;若中优先级 thread 持续运行,低优先级 owner 反而得不到 CPU 来释放 lock。阻塞式 mutex 配合 priority inheritance 等机制,可以在等待期间避免这种情况。
Two-phase lock
实践中常使用 two-phase lock:先短暂 spin,假设 owner 很快会 release;若等待超过阈值,再 park/sleep。它把 spin 的低 latency 与 blocking 的低 CPU waste 结合起来,但阈值需要根据 critical-section duration、CPU 数量和 workload 调整,不能视为普适常数。
锁实现的总原则
真实 lock 通常由三层共同构成:hardware atomic instruction 保证不可分割的状态更新;OS 提供 park、wake、wait queue 等阻塞支持;lock library 组合 fast path、slow path、fairness 与错误处理。设计时应优先实现最少而清晰的机制,再用 benchmark 和 contention profile 决定是否增加复杂优化。
Dekker 与 Peterson:只用 loads/stores 的历史方案
在 hardware atomic primitive 出现前,Dekker 与 Peterson 曾尝试只用 atomic loads/stores 构造 two-thread lock。Peterson algorithm 用 flag[] 表示每个 thread 是否想进入,用 turn 表示冲突时让谁先进入:
int flag[2];
int turn;
void init() {
flag[0] = flag[1] = 0;
turn = 0;
}
void lock() {
int self = get_thread_id();
flag[self] = 1;
turn = 1 - self;
while ((flag[1 - self] == 1) && (turn == 1 - self))
;
}
void unlock() {
flag[get_thread_id()] = 0;
}
这类 algorithm 在顺序一致的早期 hardware 上具有历史意义,但现代 architecture 的 relaxed memory consistency 会让仅依赖普通 loads/stores 的推理变得脆弱;实际系统通常直接使用 hardware atomic instructions。
Test-and-set spin lock 的边界
在 single CPU 上,spin lock 还要求 scheduler 是 preemptive 的:如果没有 timer interrupt,正在 spin 的 thread 永远不会主动让出 CPU,owner 就无法重新获得 CPU 并执行 unlock()。即使有 preemption,owner 若在 critical section 内被抢占,其他 threads 仍可能各自浪费一个 time slice 自旋。
在多 CPU 上,假设 Thread A 在 CPU 1 持有 lock、Thread B 在 CPU 2 等待,且 critical section 很短,B 的 spin 可能比一次 sleep/wakeup 更快;但 waiter 越多,反复 atomic operation 会带来更多 shared cache-line 和 cache-coherence traffic。简单 test-and-set 也没有 fairness guarantee,可能 starvation。
Ticket lock 与 progress
fetch-and-add 可以构造 ticket lock:thread 原子地领取一个 ticket 作为 myturn,只有 turn == myturn 时进入 critical section;unlock 时递增 turn:
typedef struct __lock_t {
int ticket;
int turn;
} lock_t;
void lock_init(lock_t *lock) {
lock->ticket = 0;
lock->turn = 0;
}
void lock(lock_t *lock) {
int myturn = FetchAndAdd(&lock->ticket);
while (lock->turn != myturn)
;
}
void unlock(lock_t *lock) {
lock->turn = lock->turn + 1;
}
与简单 test-and-set 不同,thread 一旦拿到 ticket,排在它前面的 threads 完成后它就会获得机会,因此 progress/fairness 更好;代价是所有等待者都会持续观察共享的 turn,高 contention 下仍有 coherence traffic。
yield():减少浪费但不解决公平性
一个中间方案是在竞争失败时调用 yield(),让 thread 从 running 状态回到 ready 状态:
void lock() {
while (TestAndSet(&flag, 1) == 1)
yield();
}
这比持续 spin 更节省 CPU,尤其是在 single CPU 上;但如果有 100 个 threads 竞争,许多 threads 仍会反复执行“尝试 acquire、yield、再次尝试”,context-switch cost 可能很高,而且它并不能消除 starvation。
Wait queue、park/unpark 与 lost wakeup
为了明确控制下一个 owner,可以为 lock 维护 waiter queue,并让失败者进入 sleep。Solaris 的 park() 会睡眠当前 thread,unpark(threadID) 唤醒指定 thread。实现中通常还需要一个短暂的 guard,保护 flag 和 queue 的更新:
lock(m):
获取 guard
如果 m->flag == 0:设置为 held,释放 guard,返回
否则:加入 waiter queue,准备 park,释放 guard,park
unlock(m):
获取 guard
若 queue 为空:设置 flag = 0
否则:直接 unpark 一个 waiter,并把 lock 交给它
释放 guard
这里不能简单地把释放 guard 放到 park() 之后,否则 owner 可能在 waiter 真正睡眠前完成 unlock,随后 waiter 才 park,造成 wakeup/waiting race(lost wakeup),最终睡眠到永远。Solaris 的 setpark() 允许 thread 先声明“即将 park”;若此时已有 unpark,后续 park() 会立即返回。另一种做法是把 guard 交给 kernel,由 kernel 原子地完成释放、入队和睡眠。
被唤醒的 thread 不一定重新把 flag 从 0 设置为 1:unlock 可以直接把 lock 的 ownership 从当前 thread transfer 给 queue 中的下一个 thread,中间不产生一个可被第三方抢走的 free 状态。
Linux futex:fast path 与 slow path
Linux 的 futex 为 user-space lock 提供 kernel support。futex_wait(address, expected) 只有在 *address == expected 时才睡眠;如果值已经变化,会立即返回。futex_wake(address) 则唤醒等待队列中的一个 thread。
futex lock 的典型设计是:无 contention 时,atomic bit test-and-set 与 release 都留在 user space;只有竞争发生时才增加 waiter count,并进入 kernel sleep/wake。一个 integer 可以同时编码 lock 是否 held 以及 waiter 数量,从而把常见的 fast path 做得很短。
Priority inversion
spin lock 还可能放大 priority inversion。低优先级 Thread 1 持有 lock 后被高优先级 Thread 3 抢占;Thread 3 随后等待该 lock。若中优先级 Thread 2 持续 runnable,scheduler 可能一直运行 Thread 2,而 Thread 1 得不到 CPU 来释放 lock,结果最高优先级的 Thread 3 反而无法继续。
常见处理方式包括避免使用 spin lock、使用 priority inheritance 临时提升 owner 的 priority,或让相关 threads 使用相同 priority。阻塞式 mutex 并不会自动解决所有 priority inversion,但比高优先级 thread 永久占用 CPU 自旋更有机会配合这些策略正确处理。
Two-phase lock
two-phase lock 先 spin 一小段时间,假设 lock 很快会释放;若仍未获得,再进入第二阶段,使用 futex 或其他 OS support park/sleep,直到 lock 可用。它试图结合 spin 的低 latency 与 blocking 的低 CPU waste,但最佳 spin 时长取决于 hardware、CPU 数量、thread 数量和 workload,没有适用于所有场景的固定阈值。
官方 Homework:x86.py locking simulation
原文的 simulation homework 使用 x86.py 观察不同 thread interleaving 如何造成或避免 race condition;具体 build/run 方法以 homework download 的 README 为准。
- 阅读
flag.s,理解它如何用一个 memory flag 实现 lock;使用默认参数运行,并用-M、-R与-c跟踪 memory variables、registers 和它们的值,预测最终flag。 - 用
-a修改各 thread 的%bx(例如两个 thread 使用-a bx=2,bx=2),观察代码行为及其对前一问预测的影响。 - 给每个 thread 设置较大的
bx,再用-i改变 interrupt frequency;找出会产生 bad outcome 与 good outcome 的参数组合。 - 阅读
test-and-set.s,说明用xchg实现 lock acquire 与 lock release 的方式;改变 interrupt interval 并循环多次,检查它是否总是正确,以及何时低效,思考如何量化浪费的 CPU。 - 使用
-P指定 schedule,例如让第一个 thread 先获得 lock、第二个 thread 随后尝试 acquire;设计还应测试哪些 interleaving? - 阅读
peterson.s,用不同-i运行,并用-a bx=0,bx=1设置正确的 thread IDs;观察不同的行为。 - 用
-P控制 schedule,尝试“证明” Peterson algorithm 满足 mutual exclusion 和 deadlock avoidance;列出需要覆盖的 cases。 - 阅读
ticket.s,确认它是否对应本章 ticket lock;用-a bx=1000,bx=1000运行,观察 threads 是否大量 spin-wait,并继续增加 thread 数量比较行为。 - 阅读
yield.s,找出test-and-set.s会浪费 cycles 而yield.s不会的场景,并估算节省的 instructions。 - 阅读
test-and-test-and-set.s,说明它做了什么,以及相对于test-and-set.s的节省来自哪里。
练习的核心是主动寻找最坏 interleaving,并分别从 correctness、fairness、CPU waste 和 scalability 评价 lock;一次成功运行不能证明 lock 在所有 schedule 下正确。
与已有笔记的关系
- OSTEP:并发导论:race condition、critical section 与 mutual exclusion 的动机。
- OSTEP:Thread API:POSIX mutex 接口。
- OSTEP:Condition Variables:基于 lock 的等待与通知。
- OSTEP:多处理器调度:多 CPU 上的 contention 与 cache effects。
参考资料
原文逐段补充
Lock 的基本语义与 POSIX mutex
lock 是一个 variable,状态通常是 available/unlocked/free 或 acquired/locked/held;后一状态下恰好一个 thread 持有它。持有 lock 的 thread 称为 owner。lock() 在 lock free 时获取它并进入 critical section;若已有 owner,调用者不会返回,直到 lock 被释放并由某个等待者获得。Locks 让 programmer 对 OS scheduler 获得最小限度的 control:scheduler 仍决定何时运行,但 lock 保证受保护代码中最多只有一个 thread active。
POSIX 将 lock 称为 mutex:
pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
Pthread_mutex_lock(&lock); // wrapper;失败时退出
balance = balance + 1;
Pthread_mutex_unlock(&lock);
把不同的 locks 传给不同的 critical sections,可以保护不同的 variables/data structures,提高 concurrency;这就是从一个 global coarse-grained lock 走向多个 fine-grained locks。
CRUX:HOW TO BUILD A LOCK
如何构建一个高效的 lock?高效 lock 以低成本提供 mutual exclusion,并可能具备其他性质。需要什么 hardware support?需要什么 OS support?本章将使用 hardware primitives 与 OS support 构建 locking library。
Figure 28.1–28.2:普通 load/store 的失败方案
typedef struct __lock_t { int flag; } lock_t;
void init(lock_t *mutex) {
// 0 -> lock is available, 1 -> held
mutex->flag = 0;
}
void lock(lock_t *mutex) {
while (mutex->flag == 1) // TEST the flag
; // spin-wait
mutex->flag = 1; // now SET it!
}
void unlock(lock_t *mutex) {
mutex->flag = 0;
}
假设 flag = 0。T1 检查到 0 后被 interrupt;T2 也检查到 0,并把 flag 设为 1;T1 恢复后同样把 flag 设为 1。两个 threads 都进入 critical section,违反 mutual exclusion:
| Thread 1 | Thread 2 |
|---|---|
call lock();while (flag == 1) | |
| interrupt,切换到 T2 | |
call lock();while (flag == 1) | |
flag = 1 | |
| interrupt,切换回 T1 | |
flag = 1(也设置成功) |
这个方案还有 performance 问题:等待者不断检查 flag(spin-wait),在 uniprocessor 上尤其浪费,因为 owner 在发生 context switch 前甚至无法运行。禁用 interrupts 也只在受控的 OS 内部场景中有用:若允许任意 application 执行 privileged disable-interrupts,它可能永久 monopolize CPU;在 multiprocessor 上其他 CPU 仍可进入 critical section;长时间屏蔽 interrupts 还可能丢失 disk/device completion 等事件。
Figure 28.3:Test-and-set spin lock
typedef struct __lock_t {
int flag;
} lock_t;
void init(lock_t *lock) {
// 0: lock is available, 1: lock is held
lock->flag = 0;
}
void lock(lock_t *lock) {
while (TestAndSet(&lock->flag, 1) == 1)
; // spin-wait
}
void unlock(lock_t *lock) {
lock->flag = 0;
}
当 flag 为 0 时,TestAndSet(&flag, 1) 原子地返回旧值 0 并写入 1,caller 不会继续 spin,获得 lock;当 flag 为 1 时,调用不断返回 1,直到 owner 将 flag 写回 0。Test 与 set 合并为单个 atomic operation,才保证只有一个 thread 能成功。
TIP:THINK ABOUT CONCURRENCY AS A MALICIOUS SCHEDULER
理解 concurrent execution 时,可以假装自己是一个恶意 scheduler:专门在最不合适的 instruction boundary interrupt threads,破坏它们脆弱的 synchronization。某个 interleaving 即使不常见,只要可能发生,就足以证明方案不正确。
Spin lock 在 single processor 上需要 preemptive scheduler;没有 preemption,正在 spin 的 thread 永远不会让出 CPU,owner 就没有机会运行并 release lock。简单 spin lock 也没有 fairness guarantee,等待者可能永远 starvation。
Dekker、Peterson 与 Figure 28.4–28.6
Dekker 和 Peterson 的历史方案只使用 loads/stores(假设它们彼此 atomic)。Peterson 的 two-thread algorithm:
int flag[2];
int turn;
void init() {
flag[0] = flag[1] = 0;
turn = 0;
}
void lock() {
int self = get_thread_id();
flag[self] = 1;
turn = 1 - self;
while ((flag[1 - self] == 1) && (turn == 1 - self))
; // spin-wait while it is not your turn
}
void unlock() {
flag[get_thread_id()] = 0;
}
这些 algorithm 在早期 hardware 上具有历史意义,但现代 relaxed memory-consistency model 使它们不能直接依赖普通 loads/stores;实际系统通常依靠专用 atomic instructions。
compare-and-swap 的原文伪代码如下:
int CompareAndSwap(int *ptr, int expected, int new) {
int original = *ptr;
if (original == expected)
*ptr = new;
return original;
}
它在 *ptr == expected 时写入 new,否则不更新,并返回原值;lock 可以写成 while (CompareAndSwap(&lock->flag, 0, 1) == 1) ;。
LL/SC 的语义是:LoadLinked 读取并建立 reservation;若从 LL 到 SC 之间没有其他 processor 对该 address 的 intervening store,StoreConditional 才写入并返回 1,否则返回 0。Figure 28.5–28.6 的核心伪代码:
int LoadLinked(int *ptr) {
return *ptr;
}
int StoreConditional(int *ptr, int value) {
if (no update to *ptr since LL to this addr) {
*ptr = value;
return 1; // success
} else {
return 0; // failed
}
}
void lock(lock_t *lock) {
while (1) {
while (LoadLinked(&lock->flag) == 1)
;
if (StoreConditional(&lock->flag, 1) == 1)
return;
}
}
void unlock(lock_t *lock) {
lock->flag = 0;
}
如果两个 threads 都先 LL 读到 0,只有一个 SC 能成功;另一个会失败并重新尝试。
Figure 28.7:Ticket lock 与 progress
typedef struct __lock_t {
int ticket;
int turn;
} lock_t;
void lock_init(lock_t *lock) {
lock->ticket = 0;
lock->turn = 0;
}
void lock(lock_t *lock) {
int myturn = FetchAndAdd(&lock->ticket);
while (lock->turn != myturn)
; // spin
}
void unlock(lock_t *lock) {
lock->turn = lock->turn + 1;
}
每个 thread 原子领取一个 ticket;只有 myturn == turn 时进入。释放时递增 turn,让下一个 waiter 进入。因此相较于 test-and-set,它为所有已领取 ticket 的 threads 提供 progress 保证,更接近 FIFO;代价是等待者持续观察共享的 turn。
TIP:LESS CODE IS BETTER CODE(LAUER’S LAW)
不要以写了多少 code 夸耀;完成同一任务所需的 code 越少、越清晰,通常越容易理解且 bug 越少。Hugh Lauer 在讨论 Pilot OS 时说:“如果同一批人有两倍时间,他们可以用一半的 code 做出同样好的 system。”
Figure 28.8–28.10:从 yield 到 queue 与 futex
yield() 将 caller 从 running 移到 ready,让其他 thread 运行:
void init() {
flag = 0;
}
void lock() {
while (TestAndSet(&flag, 1) == 1)
yield(); // give up the CPU
}
void unlock() {
flag = 0;
}
它在 two-thread/single-CPU 场景比纯 spin 好,但大量 threads 竞争时仍会产生许多 context switches,也不能解决 starvation。
Solaris 的 queue-based lock 使用 park()/unpark(threadID),并用 guard 保护 flag 与 waiter queue:
typedef struct __lock_t {
int flag;
int guard;
queue_t *q;
} lock_t;
void lock(lock_t *m) {
while (TestAndSet(&m->guard, 1) == 1)
;
if (m->flag == 0) {
m->flag = 1;
m->guard = 0;
} else {
queue_add(m->q, gettid());
setpark();
m->guard = 0;
park();
}
}
void unlock(lock_t *m) {
while (TestAndSet(&m->guard, 1) == 1)
;
if (queue_empty(m->q))
m->flag = 0;
else
unpark(queue_remove(m->q));
m->guard = 0;
}
setpark() 用于避免 wakeup/waiting race:若 thread 已声明即将 park,而另一个 thread 先 unpark,随后 park() 会立即返回。被唤醒者由 unlock 直接继承 lock,flag 不必在中间短暂变为 0。
Linux futex 的关键语义是:futex_wait(address, expected) 只有在 address 当前仍等于 expected 时才 sleep,否则立即返回;futex_wake(address) 唤醒一个 waiter。Linux lock 将无 contention 的 fast path 留在 user space,只有竞争时才进入 kernel;一个 integer 的高位可表示 held 状态,其余 bits 可记录 waiter 数量。
28.15 Different OS, Different Support:Figure 28.10
官方原文随后给出 Linux futex 的一个简化实现。它把 lock 是否 held 与 waiter 数量编码在同一个 integer 中:最高位表示 lock 状态,其余 bits 表示等待者数量;因此无 contention 的 fast path 只需要一次 atomic bit test-and-set 与一次 atomic add。
void mutex_lock(int *mutex) {
int v;
// Bit 31 was clear, we got the mutex (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;
}
// Have to wait; first make sure futex value
// we are monitoring is negative (locked).
v = *mutex;
if (v >= 0)
continue;
futex_wait(mutex, v);
}
}
void mutex_unlock(int *mutex) {
// Adding 0x80000000 to 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);
}
这里的 futex_wait(mutex, v) 仍然带有“只有值等于 expected 才睡眠”的检查,因此即使 waiter 在检查后与 unlock 发生交错,也不会因为观察到已经变化的值而无条件睡眠。原文还特别强调:这段代码来自 glibc 2.9 的 nptl lowlevellock.h,重点是 common case 的优化,而不是可直接复制到生产环境的完整 mutex 实现。
ASIDE:MORE REASON TO AVOID SPINNING — PRIORITY INVERSION
若低优先级 T1 持有 spin lock,高优先级 T3 抢占 T1 后等待该 lock,T3 会一直 spin,T1 却无法运行来 release。若中优先级 T2 也 runnable,scheduler 可能持续运行 T2,形成 priority inversion。priority inheritance 可以临时提升 lock owner 的 priority;另一个简单方案是让 threads 使用相同 priority。
two-phase lock 先 spin 一段时间,预计 lock 很快 release;若没有获得,再转入第二阶段 sleep,等待 lock free 后被唤醒。它是 hybrid approach,但合适的 spin 时间取决于 hardware、CPU 数量、thread 数量和 workload。
28.16 Two-Phase Locks
two-phase lock 的第一阶段只进行有限时间的 spinning;如果 lock 没有在这段时间内释放,caller 进入第二阶段并睡眠,直到 lock 变为可用。Linux 例子只 spin 一次,而更一般的实现可以 spin 一个固定时长后再使用 futex。这个 hybrid approach 是否更好,取决于 hardware environment、thread 数量以及 workload;不存在适用于所有 use case 的单一 general-purpose lock。
28.17 Summary
真实系统中的 lock 通常由两部分共同构成:更强的 hardware instruction,以及 operating system 提供的阻塞/唤醒支持,例如 Solaris 的 park()/unpark() 或 Linux 的 futex。具体实现会高度 tuned;要理解工程细节,可以继续阅读 Solaris 与 Linux 的 lock code,以及关于现代 multiprocessor locking strategy 的比较研究。
原文脚注 3
“像是买一本 OSTEP 的纸质版!虽然这本书可以免费在线阅读,但你难道不想在桌上放一本 hardcover 吗?或者更好,买十本送给朋友和家人?再多买一本扔向敌人?(这本书很重,所以扔出去的效果出奇地好。)”
源文档核对记录
- 官方源文档:
threads-locks.pdf,Version 1.10,共 22 页(正文至第 20 页,含封面与版权页)。 - 已核对源章节:28.1–28.17。
- 已核对图件:Figure 28.1–28.10;代码图按原文出现位置保留为 code block,概念关系按原位置保留为表格或 Mermaid。
- 原文没有需要单独下载的 raster image;本篇的“图”主要是 C 代码、执行交错和 lock 状态/调用关系。
- 已保留的关键 source details:
setpark()对 wakeup/waiting race 的修复、futex 的 expected-value 检查、单 integer 的 bit encoding、priority inheritance 与 two-phase lock。
References
- [D91] Glenn Dickey,《Just Win, Baby: Al Davis and His Raiders》,Harcourt,1991。
- [D+13] Tudor David、Rachid Guerraoui、Vasileios Trigonakis,《Everything You Always Wanted to Know about Synchronization but Were Afraid to Ask》,SOSP ’13。
- [D68] Edsger W. Dijkstra,《Cooperating sequential processes》,1968。
- [H93] Joe Heinrich,《MIPS R4000 Microprocessor User’s Manual》,Prentice Hall,1993。
- [H91] Maurice Herlihy,《Wait-free Synchronization》,ACM TOPLAS,13(1),1991。
- [L81] Hugh Lauer,《Observations on the Development of an Operating System》,SOSP ’81。
- [L09] glibc 2.9 的 Linux pthread implementation,重点是 nptl 目录。
- [M82] A. Mayer,《The Architecture of the Burroughs B5000: 20 Years Later and Still Ahead of the Times?》,1982。
- [M15] J. McCall,《OSSpinLock Is Unsafe》,2015:不同 priority 的 threads 使用 OSSpinLock 可能造成永久 spin。
- [MS91] John M. Mellor-Crummey、M. L. Scott,《Algorithms for Scalable Synchronization on Shared-Memory Multiprocessors》,ACM TOCS,9(1),1991。
- [P81] G. L. Peterson,《Myths About the Mutual Exclusion Problem》,Information Processing Letters,12(3),1981。
- [R97] Glenn E. Reeves,《What Really Happened on Mars?》:Mars Pathfinder 的 priority inversion。
- [S05] Ajay Sood,《Guide to porting from Solaris to Linux on x86》,2005。
- [S09] Sun,《OpenSolaris Thread Library》:Solaris synchronization implementation。
- [W09] 《Load-Link, Store-Conditional》:不同 architecture 的 LL/SC instruction 对照。
- [WG00] D. Weaver、T. Germond,《The SPARC Architecture Manual: Version 9》,2000。
评论 (0)