目录
正在加载目录…
正在阅读专栏 OSTEP 操作系统专栏 第 27 篇 · 共 62 篇 · 44%

OSTEP:Concurrency 总结

发布于 2026-09-17 21:40 · 最后编辑于 2026-09-17 22:08 · 版本 v2 · 字数 5,897 · 预计阅读 12 分钟 👁 21 次阅读

OSTEP:Concurrency 总结

本篇对应 OSTEP Version 1.10 concurrency 主线的 Summary。它把 thread、locks、condition variables、semaphores、concurrent data structures、common bugs 与 event-based concurrency 串成一条可复盘的知识链。

类型与定位

  • 笔记类型:总结
  • 翻译基准:官方 threads-dialogue.pdf 与第 26–33 篇正文。
  • 图件说明:总结图使用 Mermaid 重绘;没有独立 raster image。

目录

章节内容
两种并发模型threads 与 events
同步工具链lock、condition、semaphore
并发 data structurecorrectness 与 scalability
常见 bugrace、order、deadlock
解题流程从 invariant 到 measurement
复盘清单concurrency 验收标准

两种并发模型

thread-based concurrency 为每个独立执行流保存 PC、registers 和 stack,threads 共享 process address space:

mermaid
flowchart LR
  A[Process address space] --> B[Thread 1]
  A --> C[Thread 2]
  B --> D[Shared data]
  C --> D
  B --> E[Private stack/registers]
  C --> F[Private stack/registers]

event-based concurrency 用 event loop 和 state machine 管理大量 I/O 活动,handler 必须 non-blocking。前者控制流自然、适合 blocking work;后者减少 thread 与 lock overhead,但要求显式保存状态。

同步工具链

工具解决的问题关键约束
mutex/lockmutual exclusionowner、粒度、顺序
condition variable等待 predicate持锁 wait、while recheck
semaphoremutual exclusion、ordering、计数资源初值与 wait/post invariant
atomic primitive小型 read-modify-writememory ordering 与 progress
event loopI/O readiness 与状态推进handler 不得 blocking

一个完整同步方案通常包含三部分:shared state、保护 state 的机制,以及描述何时允许继续执行的 predicate/invariant。

并发 data structure

简单 single-lock 版本通常是正确起点,但可能无法扩展:

mermaid
flowchart TD
  A[Data structure] --> B[Identify shared state]
  B --> C[Define invariant]
  C --> D[Protect critical updates]
  D --> E[Measure contention]
  E --> F{性能足够?}
  F -->|yes| G[保持简单实现]
  F -->|no| H[局部锁 / batching / approximation]
  H --> E

counter 可以用 per-CPU local values 降低 contention;linked list 可以缩短锁住的范围或使用 lock coupling;queue 可以分离 head/tail locks。复杂化必须由 benchmark 证明收益。

常见 bug

Race 与 atomicity violation

多个 threads 对 shared state 的访问交错,导致结果依赖时序。检查与使用、读取与写入若应该是一个 atomic region,就必须使用同一同步协议。

Order violation

事件 B 依赖事件 A 已完成,但代码没有显式表达 A → B。用 state variable 加 condition variable/semaphore 建立 happens-before 关系。

Deadlock

四个必要条件是 mutual exclusion、hold-and-wait、no preemption、circular wait。常用处理方式是全局/部分 lock ordering、一次获取所有 locks、trylock/backoff,或 lock-free data structure。

Livelock 与 starvation

livelock 中 threads 持续运行但没有进展;starvation 中某个 thread 长期得不到资源。它们不是 deadlock,但同样是 progress/fairness 问题。

解题流程

  1. 列出 shared data 和必须保持的不变量;
  2. 枚举关键 operations 的最小 critical sections;
  3. 明确 lock、condition、semaphore 的 ownership 和获取顺序;
  4. 分析最早/最晚、成功/失败、唤醒前/后的所有 interleavings;
  5. 用 stress test、sanitizer、debugger 和 schedule tracing 复现;
  6. 测量 no contention、single CPU contention、multi-CPU contention;
  7. 只有在正确性和 progress 都成立后,再优化 scalability。

复盘清单

  • [ ] 能解释 process、thread、PC、registers、stack 与 shared address space 的关系。
  • [ ] 能说明为什么 thread creation order 不决定 execution order。
  • [ ] 能把 counter race 展开成 load/add/store 的具体 interleaving。
  • [ ] 能正确使用 lock,并说出 coarse/fine-grained trade-off。
  • [ ] 能解释 condition variable 为什么必须与 predicate、mutex 和 while 配合。
  • [ ] 能根据 invariant 推导 semaphore 初值及 wait/post 顺序。
  • [ ] 能比较 single-lock、per-CPU、lock-coupling 和 split-lock data structure。
  • [ ] 能区分 atomicity violation、order violation、deadlock、livelock 和 starvation。
  • [ ] 能解释 event loop 为什么要求 handler non-blocking,以及 state machine 如何保存进度。
  • [ ] 能在 correctness、fairness、performance 和 scalability 之间做出有证据的选择。

跨章节诊断练习

Case 1:counter 的结果偶尔错误

先把 increment() 展开成 load、add、store,列出两个 threads 交错执行时丢失 update 的 schedule;再分别用 single mutex、per-CPU approximate counter 和 atomic fetch-and-add 修复。比较三种方案的 correctness、读数精度与 contention。

Case 2:worker 偶尔永久等待

先确认等待的是 event、resource 还是 lock:如果 child 可能先完成,使用 state variable 保存完成事实;如果等待 bounded buffer 的 predicate,检查 wait 是否在持有 mutex 时进行;如果多个 locks 互相等待,绘制 resource graph 并检查 circular wait。不要只把一次“没有复现”当作修复证据。

Case 3:高并发 server 吞吐下降

分别检查 event handler 是否调用了 blocking API、thread-based server 是否出现 lock contention、single-lock data structure 是否成为瓶颈,以及多 event loops/worker pool 之间是否共享了未经保护的 state。记录 latency、throughput、CPU utilization、context switches 和 retry/wakeup 次数,再决定采用 batching、split lock、blocking worker 或 hybrid model。

一页式设计模板

设计一个 concurrent component 时,可以先填写:

项目必须回答的问题
Shared state哪些 memory/object 被多个 execution flow 访问?
Invariant任何时刻必须保持什么关系?
Progress谁在什么条件下继续?是否可能 deadlock/livelock/starvation?
Synchronization选择 lock、CV、semaphore、atomic 还是 event loop 的理由是什么?
Failure pathallocation、I/O、timeout、cancel 和异常返回时如何 cleanup?
Evidence用什么 schedule、stress test、sanitizer 和 benchmark 证明判断?

这个模板把“代码能跑”提升为可审查的同步协议:先写状态和不变量,再写 wait/acquire 与 signal/release,最后用最坏 interleaving 和实际 workload 验证。

本部分小结

OSTEP 的 concurrency 主线从“多个 execution flow 共享 state”开始,逐步引入 thread API、lock、condition variable 与 semaphore,再讨论并发 data structure、常见 bug 和 event-based model。贯穿始终的不是某个特定 API,而是三件事:明确 shared state,保护 invariant,证明 progress。

与已有笔记的关系

参考资料

官方 Summary Dialogue:Concurrency

Professor: 现在,你的脑袋是不是有点疼了?

Student:(吞下两片 Motrin)嗯,有一点。要想清楚 threads 可能发生的所有 interleaving,确实很难。

Professor: 的确如此。每当涉及 concurrent execution,我总是惊讶于:短短几行 code,竟然会变得几乎无法理解。

Student: 我也是!作为 Computer Scientist,竟然连五行 code 都弄不明白,多少有点尴尬。

Professor: 噢,也不用太难过。你如果去读最早的 concurrent algorithm 论文,会发现其中有些论文其实是错的!而且作者往往还是 professors!

Student:(倒吸一口气)Professors 也会……呃……犯错?

Professor: 是的,确实如此。不过别告诉任何人——这是我们行业的小秘密。

Student: 我发誓保密。但如果 concurrent code 这么难思考、这么难写对,我们究竟应该怎样写出正确的 concurrent code?

Professor: 这才是真正的问题,不是吗?我认为可以从几件简单的事情开始。第一,保持简单!避免 threads 之间复杂的 interaction,并使用那些管理 thread interaction 的、经过验证且广为人知的方法。

Student: 比如简单的 locking,也许再加一个 producer-consumer queue?

Professor: 正是!这些都是 common paradigm。按照你已经学到的内容,你应该能够写出可工作的 solution。第二,只有在绝对需要时才使用 concurrency;只要可能,就避免它。没有什么比对程序进行 premature optimization 更糟糕的了。

Student: 明白了——既然不需要 threads,为什么要加它们?

Professor: 没错。第三,如果你确实需要 parallelism,就尝试在其他更简单的形式中寻找它。例如,用 Map-Reduce 编写 parallel data-analysis code,就是一个很好的例子:它可以获得 parallelism,同时不必处理我们讨论过的 locks、condition variables,以及其他那些可怕的复杂性。

Student: Map-Reduce?听起来很有意思——我得自己再读一些资料。

Professor: 很好!你应该这样做。归根结底,你还必须大量自学,因为我们一起学到的内容,只能算是浩瀚知识的最初介绍。读、读,再多读一些!然后动手尝试,写 code,再多写一些。也要继续练习;这本书之外,还有大量其他资源可用¹。Gladwell 在他的书 Outliers 中提到,要真正成为 expert,大约需要投入 10,000 小时。你不可能把这些时间全都花在课堂里!

Student: 哇,我不确定这句话该让人沮丧,还是振奋。但我先把它当作后者,然后开始工作吧!是时候再写一些 concurrent code 了……

¹ 原文在这里给出了一个 gamified resource 的链接:Deadlock Empire。

这段 Dialogue 的作用不是新增一个 synchronization primitive,而是给 concurrency 主线收束:保持实现简单、避免不必要的 concurrency、优先选择 Map-Reduce 等更高层的 parallel programming model,并通过持续阅读、写 code 与练习建立正确性直觉。原文没有独立图片。

源文档核对记录

  • 官方源文档:threads-dialogue.pdf,Version 1.10,共 2 页。
  • 已逐轮核对 Professor/Student 对白、Motrin 动作、Map-Reduce 例子、10,000 小时说明和脚注 1。
  • 原文没有 Figure、表格或独立 raster image;脚注中的 Deadlock Empire 链接已保留。

Dialogue 逐段复盘

原文收束实践含义
Keep it simple先采用简单 locking、producer-consumer 等已知 pattern,减少 interleaving 的数量
Use concurrency only when needed先证明确实需要 parallelism,再承担 synchronization 与 debugging 成本
Seek simplified forms of parallelism优先考虑 Map-Reduce 等把 coordination 隐藏在 programming model 中的方案
Read, write, practice课程只能提供 bare introduction;需要用代码和实验形成可验证的经验
← 返回列表
← 上一篇 OSTEP:Event-based Concurrency 下一篇 → OSTEP:I/O Devices

评论 (0)

暂无评论,来留下第一条吧。
登录 或 注册 后才能发表评论