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

OSTEP:并发导论

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

OSTEP:并发导论

本篇对应 OSTEP Version 1.10 的 “Concurrency: An Introduction”。在 CPU 与 memory virtualization 之后,本篇引入 thread,并说明 shared data 如何在并发调度下产生 race condition。

类型与定位

  • 笔记类型:深度分析
  • 翻译基准:官方 threads-intro.pdf,Version 1.10。
  • 图件说明:原文的 address space、thread trace、counter code 与 interleaving 按原位置改写为 Mermaid、代码块和表格;没有独立 raster image。

TL;DR

  • thread 是 process 内的独立执行点:有自己的 PC、registers 和 stack,但共享 address space。
  • 使用 threads 的主要原因是 parallelism,以及将 I/O blocking 与其他 computation 重叠。
  • thread 的创建顺序不决定运行顺序;scheduler 可以产生多种合法 interleaving。
  • 多个 thread 更新 shared data 时,普通的 load/add/store 不是 atomic,可能出现 race condition。
  • critical section 需要 mutual exclusion;后续 locks、condition variables 和 semaphores 将提供同步工具。

目录

章节内容
Thread 抽象执行状态与共享资源
为什么使用 threadsparallelism 与 I/O overlap
Thread creationpthread_create() 与 join()
共享 address space多 stack 与 thread-local storage
Shared data 的问题counter race
Uncontrolled schedulinginterleaving 与 critical section
Homeworkx86.py interleaving 实验

Thread 抽象

单线程 process 可以看作只有一个执行点:一个 PC 不断取指和执行。multi-threaded process 则同时拥有多个 PC,每个 thread 都像一个小型 process,但所有 threads 共享同一个 address space。

每个 thread 私有 program counter、registers、call stack 与 stack-local variables;code、heap、global variables 与 memory mappings 则由 threads 共享。thread context switch 需要保存当前 thread 的 register state,并恢复另一个 thread 的 state;与 process switch 相比,不需要切换 page table。

mermaid
flowchart LR
  A[同一 process address space] --> B[Thread 1: PC registers stack]
  A --> C[Thread 2: PC registers stack]
  A --> D[Shared code heap globals]

为什么使用 threads

26.1 Why Use Threads?

Parallelism

在多处理器系统上,可以把大 array 的处理划分给多个 CPUs,每个 CPU 运行一个 thread。把 single-threaded 工作转换成多个 CPU 并行执行,称为 parallelization。

I/O overlap

一个 thread 因 message、disk I/O 或 page fault 阻塞时,scheduler 可以运行同一 process 中其他 ready threads。这样 computation 与 I/O 能够重叠,避免整个程序因单个慢操作停住。web server、database system 等 server application 常使用这种结构。

process 也能提供并发,但 threads 共享 address space,更方便交换数据;逻辑上独立、几乎不共享 memory 的任务则通常更适合使用 process。

Thread creation

26.2 An Example:Thread Creation

c
#include <pthread.h>

int pthread_create(pthread_t *thread,
                   const pthread_attr_t *attr,
                   void *(*start_routine)(void*),
                   void *arg);

创建 thread 后,它可能立即运行,也可能先进入 ready state;在 multiprocessor 上还可能与创建者同时运行。pthread_join() 用来等待指定 thread 完成:

c
pthread_t p1, p2;
Pthread_create(&p1, NULL, mythread, "A");
Pthread_create(&p2, NULL, mythread, "B");
Pthread_join(p1, NULL);
Pthread_join(p2, NULL);

先创建 A 再创建 B,不代表输出一定是 A、B;scheduler 可以让 B 先运行。创建顺序、开始运行顺序和完成顺序是不同概念。

共享 address space

单线程 address space 通常有一个 stack;multi-threaded process 则每个 thread 都有自己的 stack。多个 stacks 可能散布在 address space 中,stack 上的 local variables、arguments 和 return values 因而属于对应 thread 的 thread-local storage。

heap 与 global variable 仍然被所有 threads 共享,这既是 threads 便于协作的原因,也是并发 bug 的主要来源。

Shared data 的问题

26.3 Why It Gets Worse:Shared Data

考虑两个 threads 各执行 10^7 次:

c
static volatile int counter = 0;

void *mythread(void *arg) {
    for (int i = 0; i < 1e7; i++) {
        counter = counter + 1;
    }
    return NULL;
}

期望结果是 20,000,000,但实际结果可能更小,且每次运行不同。volatile 不会把复合操作变成 atomic,也不能提供 mutual exclusion。

Uncontrolled scheduling

26.4 The Heart Of The Problem:Uncontrolled Scheduling

编译器可能把 counter = counter + 1 变成:

asm
mov 0x8049a1c, %eax
add $0x1, %eax
mov %eax, 0x8049a1c

假设 counter 从 50 开始:

时刻Thread 1Thread 2counter
1load 50,add 得到 51—50
2被 interrupt,保存 register—50
3—load 50,add 得到 5150
4—store 5151
5恢复,store 自己保存的 51—51

两个 increment 最终只留下一个,原因是 scheduler 在 load/add/store 中间切换了 thread。这种结果依赖执行时序的现象称为 race condition,更具体地说是 data race;结果不可预测、跨次运行可能不同。

访问 shared variable 且不能被多个 threads 同时执行的代码区域称为 critical section。我们需要 mutual exclusion:若一个 thread 位于 critical section,其他 threads 必须被阻止进入。下一篇 OSTEP:Thread API 介绍 API,随后 OSTEP:Locks 介绍实现 mutual exclusion 的机制。

源文档逐段补充

Thread 的完整状态

thread 与 process 一样都有 PC 和 private registers,因此单个 CPU 在 T1 与 T2 之间切换时,必须把 T1 的 register state 保存到 thread control block(TCB),再恢复 T2 的 state。process context switch 还要切换 address space/page table;同一 process 内的 thread switch 通常保持 page table 不变,这正是 thread switch 的重要区别。

stack 是另一个关键差异。经典 single-threaded process 只有一个 stack,通常位于 address space 顶部并向下增长;multi-threaded process 为每个 thread 分配一个 stack。于是 stacks 可能散布在 code 与 heap 之间,破坏“heap 向上、stack 向下且二者只在空间耗尽时相遇”的简单布局。实际中 stack 通常不需要很大,只有深度 recursion 等场景会让这个问题突出。

Thread creation 的多种合法顺序

下面的 main thread 创建 T1、T2,然后分别 join 它们:

text
main: begin
create T1
create T2
join T1
join T2
main: end

可能的执行之一是 main 先创建两个 thread,T1 打印 A 后返回,T2 打印 B 后返回,两个 join 立即完成;也可能 T1 在 pthread_create() 返回前就开始运行,或者 T2 先于 T1 打印。唯一稳定的约束是 main: end 出现在两个 joined thread 都完成之后;创建顺序不保证运行顺序。

可以把 thread creation 理解为一种特殊的 function call:普通 function call 会先执行被调用函数,再返回 caller;thread creation 则建立一个独立 execution point,被调用 routine 可能在 create 返回前、也可能很久之后运行。接下来运行哪一个 thread 由 OS scheduler 决定,因此即使程序的 instruction sequence 固定,也有许多合法 interleaving。

Counter race 的低层 trace

counter = counter + 1 并不是一个 atomic action,而是 load、add、store 三步。若 counter 位于地址 0x8049a1c,x86 可能产生:

asm
mov 0x8049a1c, %eax
add $0x1, %eax
mov %eax, 0x8049a1c

当 counter 初值为 50 时,T1 可以先 load 50、add 得到 51,然后在最终 store 之前发生 timer interrupt。T2 随后也 load 50、add 得到 51 并 store;T1 恢复后再 store 它保存的 51。两个 thread 都执行了 increment,但最终 counter 只有 51,而不是正确的 52。每个 thread 的 registers 是私有的,所以 T1 与 T2 都能独立持有自己的 %eax=51;真正冲突发生在共享 memory 的 store 上。

工具是理解并发的组成部分

TIP:KNOW AND USE YOUR TOOLS

原文建议使用 objdump -d main 查看 compiler 生成的 assembly;debugger(如 gdb)、memory profiler(如 valgrind/purify)以及 compiler 本身,也都是理解和构建 systems 时应掌握的工具。

原文建议使用 disassembler 检查 compiler 生成的 instruction sequence,例如 Linux 上的:

sh
objdump -d main

还应逐步掌握 debugger(如 gdb)、memory profiler(如 valgrind)和 compiler 本身。并发 bug 往往不能只靠阅读 source code 发现;查看 assembly、控制 interleaving 和观察 memory state,才有机会把 nondeterministic 现象还原成具体执行路径。

Race、critical section 与 mutual exclusion 的严格定义

术语定义
critical section访问 shared resource(通常是 variable 或 data structure)的代码区域
race condition/data race多个 thread 几乎同时进入该区域并更新 shared state,结果取决于执行时序
indeterminate程序包含 race,输出不再由输入唯一决定,可能每次运行不同
mutual exclusion任意时刻至多一个 thread 位于受保护的 critical section

这里的“不可预测”不是说 hardware 随机出错,而是 scheduler 可以在多个合法位置发生 context switch;不同的 interrupt timing 让不同 interleaving 成为可能。

Atomicity:all or nothing

理想情况下,若硬件提供如下 atomic instruction,就可以直接完成 counter update:

asm
memory-add 0x8049a1c, $0x1

atomic 的含义是“作为一个整体”:interrupt 要么发生在 instruction 执行前,要么发生在执行完成后,不会暴露中间状态。现实中硬件不会为任意 data structure(例如 concurrent B-tree)提供专用 atomic instruction,而是提供少量基础 atomic primitives;OS 再结合它们构造 locks、semaphores 等 synchronization primitives。

atomicity 也不仅属于 concurrency。file system 的 journaling、copy-on-write,以及 database transaction 都在更大范围内使用“all or nothing”的思想,在 failure 或并发执行下隐藏不完整的中间状态。

TIP:USE ATOMIC OPERATIONS

atomic operation 是构建 computer architecture、concurrent code、file system 和 distributed system 的基础 technique。把一系列 actions 组合成 atomic operation,就是让它呈现为“all or nothing”:要么全部发生,要么全部没有发生,中间状态不会被其他 execution point 看到。在 database 中,这种 grouping 通常称为 transaction;在 file system 中,journaling 与 copy-on-write 也使用相同思想。

另一类 interaction:等待与唤醒

并发不只有“同时访问 shared data”。常见的另一类 interaction 是一个 thread 必须等待另一个 thread 完成某个 action,例如 disk I/O 完成后,等待的 thread 才能继续。此时需要 sleep/wakeup mechanism:等待 I/O 的 thread 进入 blocked/sleeping state,I/O 完成后被唤醒并重新进入 runnable state。后续 condition variables 等章节会系统讨论这种等待关系。

为什么这属于 operating systems

OS 本身就是最早的大型 concurrent program 之一。两个 process 同时执行 write() 并 append 同一个 file 时,kernel 可能同时更新 free-block bitmap、file inode、block pointer 与 file size;这些更新必须位于正确的 critical section 中,否则 interrupt 会留下损坏的 file-system state。

同样的同步要求适用于 page tables、process lists、file-system structures 以及几乎所有 kernel data structure。后来 multi-threaded application 也必须面对同类问题,但许多 synchronization technique 最初正是为 OS 内部的并发更新而发展出来的。

并发模拟实验

原文使用 x86.py 模拟不同 thread interleaving。实验重点包括:

  1. 用单 thread 运行 loop.s,观察 %dx 在每条 instruction 后的值;
  2. 用两个 thread 初始化相同 registers,比较固定与随机 interrupt interval;
  3. 运行 looping-race-nolock.s,观察 address 2000 的 shared variable 在不同 seed、loop count 和 interrupt interval 下的最终值;
  4. 找出 increment critical section 的确切三条 instruction 边界,以及哪些 interrupt 位置安全、哪些会丢失更新;
  5. 运行 wait-for-me.s,观察一个 thread 如何通过 register 和 memory location 2000 等待另一个 thread,并判断 CPU 是否被低效 busy-wait 占用。

这些实验的目的不是背诵某个输出,而是训练从 instruction-level interleaving 推导 shared state 结果,并认识到“interrupt frequency”本身不是 synchronization:只有正确的 atomic primitive 或 mutual exclusion 才能保证结果。

Homework

使用 x86.py 观察不同 thread interleavings 如何产生或避免 race condition,具体选项见其 README。

  1. 阅读并运行 loop.s:./x86.py -t 1 -p loop.s -i 100 -R dx。预测运行期间 %dx 的值,并用 -c 检查。
  2. 使用 ./x86.py -p loop.s -t 2 -i 100 -a dx=3,dx=3 -R dx,观察两个 threads 各自将 %dx 初始化为 3 后的 values。多个 threads 是否改变计算?这里有 race 吗?
  3. 使用 ./x86.py -p loop.s -t 2 -i 3 -r -R dx -a dx=3,dx=3,改变 random seed(-s)观察 interleavings。interrupt frequency 会改变结果吗?
  4. 使用单 thread 运行 ./x86.py -p looping-race-nolock.s -t 1 -M 2000,确认 shared variable(memory address 2000)在整个运行过程中的值,并用 -c 检查。
  5. 运行 ./x86.py -p looping-race-nolock.s -t 2 -a bx=3 -M 2000。为什么每个 thread loop 三次?最终的 shared value 是多少?
  6. 使用 ./x86.py -p looping-race-nolock.s -t 2 -M 2000 -i 4 -r -s 0,再换不同 seeds。能否只根据 interleaving 预测最终 value?interrupt 在哪些位置安全、哪些位置会造成丢失更新?critical section 的准确边界在哪里?
  7. 使用固定 interrupt interval:./x86.py -p looping-race-nolock.s -a bx=1 -t 2 -M 2000 -i 1,然后改变 -i 2、-i 3 等。最终 value 是多少?哪些 intervals 会得到正确答案?
  8. 将 loops 增加到 -a bx=100,研究哪些 interrupt intervals(-i)仍能得到正确结果,哪些结果出人意料。
  9. 运行 wait-for-me.s:./x86.py -p wait-for-me.s -a ax=1,ax=0 -R ax -M 2000。解释 code 的行为、memory address 2000 的用途和最终 value。
  10. 交换 inputs:./x86.py -p wait-for-me.s -a ax=0,ax=1 -R ax -M 2000。两个 threads 如何运行?thread 0 在做什么?改变 interrupt interval(例如 -i 1000 或 random interval)会如何影响 trace?这个程序是否高效利用了 CPU?

与已有笔记的关系

参考资料

原文逐段补充

Figure 26.1:Single-Threaded And Multi-Threaded Address Spaces

single-threaded process 通常只有一个 stack;multi-threaded process 则为每个 thread 配置一个 stack。多个 stack 可能分散在 address space 中,stack-local variables、arguments 与 return values 都属于相应 thread 的 thread-local storage。

mermaid
flowchart TB
  A[Single-threaded address space] --> A1[Stack]
  A --> A2[Free]
  A --> A3[Heap]
  A --> A4[Program code]
  B[Multi-threaded address space] --> B1[Stack 1]
  B --> B2[Stack 2]
  B --> B3[Free]
  B --> B4[Heap]
  B --> B5[Program code]

这会破坏原先“heap 与 stack 可以独立增长,只有 address space 用尽时才相遇”的布局。不过通常问题不大,因为 stack 一般不需要很大;大量 recursion 是较明显的例外。

Figure 26.2–26.5:Thread creation 与合法 trace

原文的完整 t0.c 如下;Pthread_create() 与 Pthread_join() 是在失败时退出的 wrapper:

c
#include <stdio.h>
#include <assert.h>
#include <pthread.h>
#include "common.h"
#include "common_threads.h"

void *mythread(void *arg) {
    printf("%s\n", (char *) arg);
    return NULL;
}

int main(int argc, char *argv[]) {
    pthread_t p1, p2;
    int rc;
    printf("main: begin\n");
    Pthread_create(&p1, NULL, mythread, "A");
    Pthread_create(&p2, NULL, mythread, "B");
    // join waits for the threads to finish
    Pthread_join(p1, NULL);
    Pthread_join(p2, NULL);
    printf("main: end\n");
    return 0;
}

pthread_join() 会等待指定 thread 完成,因此 main: end 一定在 T1、T2 都返回之后出现。但输出 A、B 的顺序没有保证:thread 可能在 create 返回前就开始运行,也可能晚些时候运行;即便 T1 先创建,scheduler 也可以让 T2 先打印 B。

三个原文 trace 的共同约束只有一个:两个 joined threads 完成后,main 才能继续。Figure 26.3 中 main 先创建 T1/T2,再依次看到 A、B;Figure 26.4 中 T1、T2 在各自创建后立刻运行,两个 join 随后立即返回;Figure 26.5 中 T2 先于 T1 运行并打印 B。

Figure 26.6:完整的 shared-data 示例

两个 worker thread 各执行 10^7 次 counter = counter + 1,期望结果是 20,000,000。原文完整程序使用 volatile,但这并不使复合更新成为 atomic:

c
#include <stdio.h>
#include <pthread.h>
#include "common.h"
#include "common_threads.h"

static volatile int counter = 0;

void *mythread(void *arg) {
    printf("%s: begin\n", (char *) arg);
    int i;
    for (i = 0; i < 1e7; i++) {
        counter = counter + 1;
    }
    printf("%s: done\n", (char *) arg);
    return NULL;
}

int main(int argc, char *argv[]) {
    pthread_t p1, p2;
    printf("main: begin (counter = %d)\n", counter);
    Pthread_create(&p1, NULL, mythread, "A");
    Pthread_create(&p2, NULL, mythread, "B");
    Pthread_join(p1, NULL);
    Pthread_join(p2, NULL);
    printf("main: done with both (counter = %d)\n", counter);
    return 0;
}

一次看似正确的运行:

text
prompt> gcc -o main main.c -Wall -pthread; ./main
main: begin (counter = 0)
A: begin
B: begin
A: done
B: done
main: done with both (counter = 20000000)

但也可能出现以下错误结果,并且每次运行不同:

text
prompt> ./main
main: done with both (counter = 19345221)
prompt> ./main
main: done with both (counter = 19221041)

Figure 26.7:The Problem: Up Close and Personal

当 counter 位于 0x8049a1c 时,compiler 可能生成:

asm
100  mov 0x8049a1c, %eax
105  add $0x1, %eax
108  mov %eax, 0x8049a1c

假设 counter 初值为 50:T1 load 50 并 add 得到 51 后发生 timer interrupt;OS 保存 T1 的 PC 与 registers 到 TCB,切换到 T2。T2 也 load 50、add 得到 51 并 store,counter 变成 51;T1 恢复后把自己保存的 51 再次 store。两个 increment 都执行了,但 counter 只有 51,正确值应为 52。

执行后OSThread 1Thread 2PCeaxcounter
before critical section100050
mov 8049a1c,%eax1055050
add $0x1,%eax1085150
interrupt;save T1;restore T2save/restoresuspendedrunning100050
mov 8049a1c,%eax1055050
add;mov %eax,8049a1c1135151
interrupt;save T2;restore T1save/restoreresumedsuspended1085151
mov %eax,8049a1c1135151

这种结果称为 race condition,更具体地说是 data race;它依赖执行 timing,因此 output 是 indeterminate。访问 shared variable 且不能被多个 threads 同时执行的区域就是 critical section;所需性质是 mutual exclusion,即一个 thread 在 critical section 中时,其他 threads 必须被阻止进入。这些术语与早期 concurrency 研究者 Edsger Dijkstra 的工作密切相关,尤其是 1968 年的 “Cooperating Sequential Processes” [D68]。

Atomicity 与同步问题

atomic operation 是构建 computer architecture、concurrent code、file system、database system 和 distributed system 的基础。Atomic 的意思是“作为一个整体”,也就是一组 actions 要么全部发生,要么全部没有发生,其他 execution point 看不到中间状态;database 中常把这种组合称为 transaction。

一种理想的 hardware instruction 可以是:

asm
memory-add 0x8049a1c, $0x1

若硬件保证它 atomic,interrupt 要么发生在 instruction 尚未执行时,要么发生在执行完成后。可是 hardware 不会为 concurrent B-tree 提供“atomic update of B-tree”这样的专用 instruction;实际做法是提供少量基础 atomic primitives,再结合 OS 构建通用 synchronization primitives。File system 的 journaling 与 copy-on-write 也在 failure 下使用同样的 all-or-nothing 思路。

CRUX:HOW TO SUPPORT SYNCHRONIZATION

构建有用的 synchronization primitives 需要 hardware 提供什么支持?OS 需要提供什么支持?如何正确且高效地构造这些 primitives?Program 应该如何使用它们来得到期望结果?

并发还有另一类 interaction:一个 thread 必须等待另一个 thread 完成 action。例如 process 发起 disk I/O 后进入 sleeping state,I/O 完成时需要被唤醒。因此后续章节不仅讨论保证 atomicity 的 synchronization primitives,也讨论支持 sleep/wakeup 的机制;condition variables 会具体介绍这种等待关系。

ASIDE:KEY CONCURRENCY TERMS

  • critical section:访问 shared resource(通常是 variable 或 data structure)的代码区域。
  • race condition/data race:多个 threads 大致同时进入 critical section 并尝试更新 shared data,产生意外结果。
  • indeterminate:含有一个或多个 race condition 的 program;output 取决于哪些 threads 在何时运行。
  • mutual exclusion:保证任意时刻只有一个 thread 进入 critical section,从而避免 race 并得到确定性 output。

为什么在 operating systems 课程中学习 concurrency

OS 是最早的大型 concurrent program,许多 technique 最初就是为 OS 内部使用而创造的。假设两个 process 同时调用 write(),都要把 data append 到同一个 file:它们需要分配新 block,在 inode 中记录 block 位置,并更新 file size。由于 interrupt 可以发生在任意时刻,更新 allocation bitmap、inode、page tables、process lists 和其他 kernel data structures 的代码都必须是正确同步的 critical sections。后来出现 multi-threaded application,application programmers 也必须处理同类问题。

源文档核对记录

官方 Version 1.10 的 threads-intro.pdf 共 16 页,包含 Figure 26.1–26.7。当前笔记已保留 thread address-space 图、t0.c/t1.c、三条 thread trace、shared-counter 输出、assembly interleaving、atomicity/mutual-exclusion 术语与 x86.py homework;原文没有独立 raster image。

References

  • [D65] E. W. Dijkstra,《Solution of a problem in concurrent programming control》,Communications of the ACM,8(9):569,1965:早期 mutual exclusion 问题及其解法。
  • [D68] Edsger W. Dijkstra,《Cooperating sequential processes》,1968:原文。
  • [GR92] Jim Gray、Andreas Reuter,《Transaction Processing: Concepts and Techniques》,Morgan Kaufmann,1992。
  • [L+93] Nancy Lynch 等,《Atomic Transactions》,Morgan Kaufmann,1993。
  • [NM92] Robert H. B. Netzer、Barton P. Miller,《What Are Race Conditions? Some Issues and Formalizations》,ACM Letters on Programming Languages and Systems,1(1),1992。
  • [SR05] W. Richard Stevens、Stephen A. Rago,《Advanced Programming in the UNIX Environment》,Addison-Wesley,2005。
← 返回列表
← 上一篇 OSTEP:VM 总结 下一篇 → OSTEP:Thread API

评论 (0)

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