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

OSTEP:Semaphores

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

OSTEP:Semaphores

本篇对应 OSTEP Version 1.10 的 “Semaphores”。semaphore 是一个可同时表达 mutual exclusion、ordering 和 resource counting 的同步 primitive。

类型与定位

  • 笔记类型:深度分析
  • 翻译基准:官方 threads-sema.pdf,Version 1.10。
  • 图件说明:原文的 semaphore definition、thread trace、producer/consumer 与 reader/writer 代码按原位置保留为代码块、表格和 Mermaid;没有独立 raster image。

TL;DR

  • semaphore 有一个 integer value,由 atomic 的 wait 与 post 操作修改。
  • wait 将 value 减一,若结果为负则阻塞;post 将 value 加一,并在存在 waiter 时唤醒一个。
  • 初值为 1 的 binary semaphore 可以实现 lock。
  • semaphore 也能表达 event ordering、producer/consumer、reader/writer 等模式。
  • 使用 semaphore 时,初值、wait/post 的位置和 invariant 必须一起推导,不能靠直觉填写。

目录

章节内容
Semaphore 定义wait/post 与 integer value
Binary semaphore用 semaphore 实现 lock
Orderingparent 等待 child
Producer/consumerempty/full 与 mutex
Reader/writer读者共享与写者排他
使用要点初值与 invariant

Semaphore 定义

POSIX 接口是:

c
#include <semaphore.h>

sem_t s;
sem_init(&s, 0, initial_value);
sem_wait(&s);
sem_post(&s);

可以把操作抽象为:

c
int sem_wait(sem_t *s) {
    decrement the value of semaphore s by one;
    wait if value of semaphore s is negative;
}

int sem_post(sem_t *s) {
    increment the value of semaphore s by one;
    if there are one or more threads waiting, wake one;
}

多个 threads 可能同时调用 wait/post,所以这些更新必须具有 atomic semantics。value 为负时,其绝对值可对应等待中的 thread 数量;实现细节对 user 隐藏,但这个 invariant 有助于理解行为。

Binary semaphore

初值为 1 的 semaphore 可作为 lock:

c
sem_t m;
sem_init(&m, 0, 1);

sem_wait(&m);
    // critical section
sem_post(&m);

第一个 thread wait 后 value 从 1 变为 0,立即进入 critical section。第二个 thread wait 后 value 从 0 变为 -1,进入 sleep。第一个 thread post 后 value 恢复为 0,并唤醒一个 waiter;被唤醒者随后进入 critical section。

这就是 binary semaphore:它在 lock 场景中主要表示“一个许可是否可用”,但 generalized semaphore 还可以表示多个同类资源。

Ordering

semaphore 可以表达“一个事件必须先发生”的关系。parent 等待 child 完成为例:

c
sem_t s;

void *child(void *arg) {
    printf("child\n");
    sem_post(&s);
    return NULL;
}

int main() {
    sem_init(&s, 0, 0);
    printf("parent: begin\n");
    pthread_t c;
    Pthread_create(&c, NULL, child, NULL);
    sem_wait(&s);
    printf("parent: end\n");
}

初值必须是 0:parent 先 wait 时 value 变为 -1 并睡眠;child post 后 value 加一并唤醒 parent。若 child 先 post,value 从 0 变为 1,之后 parent wait 会消耗这个许可并立即返回,因此不会发生 lost wakeup。

Producer/consumer

bounded buffer 通常使用:

  • 一个 binary semaphore/mutex 保护 buffer 的 critical section;
  • 一个 counting semaphore empty,表示可用 slots 数;
  • 一个 counting semaphore full,表示已有 items 数。

producer 先 wait empty,再取得 mutex、放入 item、释放 mutex,最后 post full;consumer 先 wait full,再取得 mutex、取出 item、释放 mutex,最后 post empty。

mermaid
flowchart LR
  A[Producer] --> B[wait empty]
  B --> C[wait mutex]
  C --> D[put item]
  D --> E[post mutex]
  E --> F[post full]
  G[Consumer] --> H[wait full]
  H --> I[wait mutex]
  I --> J[get item]
  J --> K[post mutex]
  K --> L[post empty]

顺序很重要:若 producer 在 buffer 满时持有 mutex 再等待 empty,consumer 无法获得 mutex 去取出 item,会产生 deadlock。

初值的通用判断

选择 semaphore 初值时,可以问:“初始化完成后,准备立即交出的 resource 有多少?”

  • 用作 lock 时,立即交出一个许可,所以初值为 1;
  • 用于 parent 等待 child 时,事件尚未发生,没有许可,所以初值为 0;
  • 对容量为 MAX 的 bounded buffer,开始时有 MAX 个 empty slots,因此 empty = MAX,而 full = 0。

这个判断比记忆某个例子的数字更可靠:semaphore value 表示当前可以被 wait 消耗的许可数量;当事件先于等待发生时,post 会留下许可,之后的 wait 仍能正确通过。

bounded buffer 的错误加锁方式

empty 与 full 只负责描述 buffer 的状态,fill、use 以及 buffer 内容仍需要 mutual exclusion。一个常见错误是让 consumer 先取得 mutex,再在 full 上 wait。若 buffer 为空,consumer 会睡眠但继续持有 mutex;producer 为了放入 item 又必须 wait mutex,于是形成环:consumer 等待 full,producer 等待 mutex。

正确结构是先等待资源条件,再只在真正访问 buffer 的短 critical section 中获取 mutex:

c
sem_wait(&empty);
sem_wait(&mutex);
put(item);
sem_post(&mutex);
sem_post(&full);

consumer 对称地先 wait(full),再取得 mutex、执行 get()、释放 mutex,最后 post(empty)。把 mutex 放在 put()/get() 内部也可以更模块化,但必须保持同样的等待顺序。

Reader/writer

reader/writer 问题中,多个 readers 可以并行读取,但 writer 需要排他访问。semaphore 可以保护 reader count,并让第一个 reader 获得 writer exclusion、最后一个 reader 释放它:

c
sem_t rw_mutex;
sem_t mutex;
int readers = 0;

void begin_read() {
    sem_wait(&mutex);
    readers++;
    if (readers == 1)
        sem_wait(&rw_mutex);
    sem_post(&mutex);
}

void end_read() {
    sem_wait(&mutex);
    readers--;
    if (readers == 0)
        sem_post(&rw_mutex);
    sem_post(&mutex);
}

void write() {
    sem_wait(&rw_mutex);
    // exclusive critical section
    sem_post(&rw_mutex);
}

这个基本方案可能让 writer starvation;公平性需要额外的 turnstile/queue 设计。

reader-writer lock 的核心 invariant 是:readers > 0 时,rw_mutex 被第一个 reader 持有;只有最后一个 reader 离开时才释放它。因此 readers 之间不互相排斥,而 writer 与整个 reader group 互斥。该实现可能在 writer 已经等待时继续接纳新 readers,形成 reader-preference;若要避免 writer starvation,需要在入口设置 turnstile,使等待中的 writer 阻止后续 readers 穿过。更复杂的 reader-writer lock 也可能因为 bookkeeping 和 wakeup 成本而不如简单 lock。

使用要点

  • 先写出 invariant,再决定 semaphore 初值;
  • 把 wait/post 看成 acquire/release 或 consume/produce 的配对;
  • 检查每条可能的执行顺序,尤其是 signal/event 先发生的情况;
  • 多个 semaphore 的获取顺序必须固定,避免 deadlock;
  • 区分 binary semaphore、counting semaphore 与 condition variable 的语义;
  • 测试单线程、竞争、异常退出和资源耗尽场景。

源文档逐段补充

semaphore 的来源与精确定义

semaphore 用一个 integer value 加上两个 atomic operation 表达同步。历史上 Dijkstra 将 sem_wait() 称为 P()、sem_post() 称为 V();也有人称它们为 down/up。sem_init(&s, 0, value) 的第二个参数为 0 时,表示 semaphore 在同一 process 的 threads 间共享;其他设置可用于跨 process 的同步。

抽象语义是:sem_wait() 先将 value 减一,若结果小于 0 则阻塞 caller;sem_post() 将 value 加一,若存在 waiter 则唤醒其中一个。多个 waiter 可以排队睡眠。Dijkstra 风格实现中,value 为负时,其绝对值等于等待 thread 数;有些现代实现(包括本章后面构造的版本)选择不让 value 低于 0,而是将 waiter 数量隐藏在内部状态中。

Binary semaphore 的执行轨迹

以初值 1 的 semaphore 为例:第一个 thread wait 后 value 从 1 变为 0,立即进入 critical section;第二个 thread wait 后 value 变为 -1 并 sleep。第一个 thread post 将 value 加回 0,唤醒第二个 thread;第二个 thread 从 wait 返回并进入 critical section,最后 post 使 value 恢复为 1。若没有 waiter,post 只是把一个许可留在 semaphore 中。

因此 binary semaphore 可以表现为 lock 的两个状态,但 generalized counting semaphore 能表达多个同类 resource。初值的通用思考方式是:初始化后系统愿意立即“发放”多少个 resource?lock 是 1,尚未发生的 event 是 0,容量为 MAX 的空 buffer 是 MAX。

Ordering 的两种时序

parent 等待 child 时,s 的初值必须为 0:

text
Case 1: parent wait 先发生
s = 0 → parent wait → s = -1,parent sleep
child post     → s = 0,唤醒 parent

Case 2: child post 先发生
s = 0 → child post → s = 1
parent wait    → s = 0,立即返回

第二种时序说明 semaphore 与没有 state variable 的 condition signal 不同:event 先发生时,post 会留下一个许可,不会丢失 wakeup。

Bounded buffer:先等 resource,再取得 mutex

单纯用 empty 与 full 只解决“是否有空 slot/已有 item”,并不保护 fill、use 和 buffer 内容。多个 producer 可能同时更新 buffer[fill] 与 fill,因此 put 是 critical section;多个 consumer 同理。

错误的加锁顺序是让 producer 先取得 mutex、再等待 empty,让 consumer 先取得 mutex、再等待 full:

text
consumer 持有 mutex,等待 full(buffer empty)
producer 等待 mutex,无法 put item 并 post full
→ 两者互相等待,deadlock

正确顺序是先等待资源 semaphore,再只在短 critical section 中取得 binary semaphore:

c
// producer
sem_wait(&empty);
sem_wait(&mutex);
put(item);
sem_post(&mutex);
sem_post(&full);

// consumer
sem_wait(&full);
sem_wait(&mutex);
item = get();
sem_post(&mutex);
sem_post(&empty);

对于 MAX > 1 的 ring buffer,empty 初值为 MAX、full 初值为 0;fill 与 use 按 modulo 前进。mutex 可以放在 put/get 内部以提高模块化,也可以由调用者包围,但必须确保 resource wait 不会在持有 mutex 时阻塞。

Reader-writer lock 的公平性

reader-writer lock 的基本实现用 readers 记录当前 reader 数量,用一个 semaphore 保护该计数,用 writelock 阻止 writer:第一个 reader wait writelock,其余 readers 只增加计数;最后一个 reader post writelock。writer 直接 wait/post writelock。

这种 reader-preference 版本允许 writer 等待期间仍有新的 reader 进入,因此可能 writer starvation。可以加入 turnstile 或其他入口队列:一旦 writer 等待,后续 readers 不能继续穿过。更复杂的公平实现也会增加 bookkeeping 和 wakeup overhead,所以 reader-writer lock 并不一定比简单 mutex 更快。

Dining philosophers 与 deadlock

五位 philosopher 围桌而坐,每两人之间有一把 fork;每人必须同时取得 left/right 两把 fork 才能 eat:

c
while (1) {
    think();
    get_forks(p);
    eat();
    put_forks(p);
}

若所有 philosopher 都先 wait 左 fork,再 wait 右 fork,就可能形成环:每人持有一把 fork 并等待邻居持有的另一把,所有人永久阻塞。一个简单修复是让最后一个 philosopher 先取得 right 再取得 left,打破 circular-wait dependency。这个例子说明 semaphore 能表达 resource ownership,但不自动消除 deadlock;获取多个 semaphore 时仍需设计全局顺序。

Thread throttling

semaphore 也可用于 admission control。假设程序创建了数百个 worker,但每个 worker 进入某段 memory-intensive region 都会大量分配 memory;若全部同时进入,physical memory 可能耗尽并引发 thrashing。将 semaphore 初值设为允许同时进入的最大 thread 数,并在该区域前后执行 wait/post,即可限制并发度:

c
sem_wait(&slots);
memory_intensive_work();
sem_post(&slots);

这不是为了保护某个 data structure,而是主动把 resource demand 控制在系统可承受范围内。

用 lock 与 condition variable 实现 semaphore

可以用一把 mutex、一个 condition variable 和一个非负 value 构造简化版 Zemaphore:

c
typedef struct {
    int value;
    pthread_cond_t cond;
    pthread_mutex_t lock;
} Zem_t;

void Zem_wait(Zem_t *s) {
    Mutex_lock(&s->lock);
    while (s->value <= 0)
        Cond_wait(&s->cond, &s->lock);
    s->value--;
    Mutex_unlock(&s->lock);
}

void Zem_post(Zem_t *s) {
    Mutex_lock(&s->lock);
    s->value++;
    Cond_signal(&s->cond);
    Mutex_unlock(&s->lock);
}

这个版本与 Dijkstra 原始定义的差异是 value 不会为负,因此不能直接用负值推导 waiter 数量;它更接近现代 Linux semaphore 的内部行为。反过来,用 semaphore 实现完整 condition variable 更困难,尤其要正确处理 predicate、唤醒时序和 lost wakeup。

Generalization 的边界

semaphore 可以看成 lock 与 condition variable 的 generalization,但“一个 primitive 能表达更多模式”不等于所有场景都应该统一使用它。抽象有价值时可以减少机制数量;抽象过度时会掩盖 predicate、ownership 和 wakeup 语义。实践中要根据问题选择最清晰的 primitive,并警惕为了通用而增加不必要的复杂度。

官方 Code Homework:用 semaphore 解决经典同步问题

原文的 Code Homework 要求在给定 code skeleton 中补写 semaphore 逻辑。Linux 可以直接使用 native semaphore;macOS 没有相同的支持时,应先按照本章的方式用 lock 与 condition variable 实现一个 semaphore。每个练习都应同时验证不同的 thread interleaving,而不是只观察一次成功输出。

  1. 实现并测试 fork/join。子 thread 中加入 sleep(1),确认 parent 确实等待 child 完成;对应 skeleton 为 fork-join.c。
  2. 实现 rendezvous:两个 threads 都必须到达 rendezvous point 后,任何一个才能离开该段代码。使用两个 semaphore;对应 rendezvous.c。
  3. 实现 reusable barrier:对已知的 N 个 threads,保证所有 threads 都执行完 P1 后,任何 thread 才能执行 P2。使用两个 semaphore 与计数变量;对应 barrier.c。
  4. 实现不考虑 starvation 的 reader-writer problem(reader-writer.c),加入 sleep() 验证 reader 并行、writer 排他的行为,并构造 writer starvation。
  5. 修改 reader-writer solution,使 readers 与 writers 都 eventually make progress,消除 starvation;对应 reader-writer-nostarve.c。
  6. 用 semaphore 构造 no-starve mutex,使任何尝试 acquire 的 thread 最终都能获得 mutex;对应 mutex-nostarve.c。
  7. 继续阅读 Downey 的 The Little Book of Semaphores,用更多 puzzle 练习初值、计数、barrier、rendezvous 与 fairness 的推导。

验收思路

  • fork/join 要覆盖 child 先 post 与 parent 先 wait 两种顺序。
  • rendezvous/barrier 要检查“过早离开”是否可能发生,以及 barrier 是否可重复使用。
  • reader-writer 不只验证 mutual exclusion,还要观察 reader-preference 是否让 writer 长期得不到机会。
  • no-starve mutex 要说明 semaphore queue/order 是否真的提供 progress,而不是把某次 scheduler 行为误当作公平性保证。

本章小结

semaphore 用一个 integer value 与 atomic 的 wait/post 统一表达许可、事件顺序和资源数量。初值为 1 时可以表达 binary lock,初值为 0 时可以保存尚未发生的 ordering event,初值为 MAX 时可以表达 bounded buffer 的空 slots。它还能构造 reader-writer lock、dining philosophers 的 resource protocol 与 thread throttling。

但 generalization 也会隐藏语义:使用 semaphore 前仍需明确 resource ownership、predicate、获取顺序和 progress/fairness。semaphore 可用于实现 lock 与 condition variable,而反向从 semaphore 实现 condition variable 更容易出错;“更通用”不自动意味着“更简单”。

与已有笔记的关系

参考资料

原文逐段补充:Figure 31.1–31.17 与遗漏旁注

31.1 Semaphores: A Definition:历史与 CRUX

这一章以 Dijkstra 对 semaphore 的工作为起点。semaphore 不只是“带一个整数的 lock”,而是一个可以保存许可(permit)或事件的同步 primitive。

CRUX:如何使用 semaphore

如何用 semaphore 构造常见的同步模式?如何用它实现 ordering、互斥、条件同步、bounded buffer、reader-writer lock,以及其他并发协议?

Figure 31.1:初始化一个 semaphore

c
sem_t s;
Sem_init(&s, 0, 1); // what should the initial value be?

这里的第二个参数表示 semaphore 是否在多个 processes 间共享;本章的 thread 示例使用 0。第三个参数是初始 value,必须结合协议的含义选择,而不是机械地都设成 1。

Figure 31.2:Semaphore 的定义

c
// semaphore value is an integer
int value;

wait() {
    value--;
    if (value < 0) {
        add this thread to waiting queue;
        block();
    }
}

post() {
    value++;
    if (value <= 0) {
        remove a thread from waiting queue;
        wakeup(thread);
    }
}

wait() 和 post() 必须是 atomic 的。上面是教材用来解释语义的抽象实现;真实系统会用底层 atomic instruction、scheduler 和 wait queue 完成它。P 与 V 是 Dijkstra 使用的命名:P 来自荷兰语 proberen(尝试),V 来自 verhogen(增加)。后来也常见 down/up、wait/post 等名称。

31.2 Binary Semaphores(Locks):Figure 31.3–31.5

c
sem_t s;
Sem_init(&s, 0, 1); // initially unlocked

void *child(void *arg) {
    wait(&s);
    // critical section
    post(&s);
    return NULL;
}

当初始值为 1 时,第一个 thread 执行 wait() 后 value 变为 0,可以进入 critical section;其他 thread 的 wait() 会阻塞。拥有许可的 thread 执行 post() 后,value 恢复为 1,等待者中至多一个被唤醒。

一个典型的执行轨迹如下:

时刻操作value结果
t0wait()0进入 critical section
t1wait()-1加入等待队列并阻塞
t0post()0唤醒 t1
t1继续执行0进入 critical section

Figure 31.4 的单 thread trace 保留为:

semaphore valueThread 0
1初始状态
1call sem_wait()
0sem_wait() returns,进入 critical section
0critical section
0call sem_post()
1sem_post() returns

Figure 31.5 的双 thread trace:

valueThread 0Thread 1
1Run;准备调用 sem_wait()Ready
1call sem_wait()Ready
0sem_wait() returns;进入 critical sectionReady
0critical sectionReady
0interrupt,切换到 T1Run;准备调用 sem_wait()
-1Readysem_wait() decrement,因 value<0 进入 Sleep
-1切换回 T0Sleep
-1critical section 结束,call sem_post()Sleep
0sem_post(),wake(T1)Ready
0sem_post() returnsReady
0interrupt,切换到 T1Run;sem_wait() returns
0Ready进入 critical section
0Readycall sem_post()
1Readysem_post() returns

因此,binary semaphore 可以实现 lock,但它与普通 lock 仍有重要差异:semaphore 没有天然的 ownership 约束,任何 thread 都可能调用 post();lock 通常要求由持有者释放。

31.3 Semaphores for Ordering:Figure 31.6–31.8

当 semaphore 初始值为 0 时,它可以保存“某件事尚未发生”的信息:

c
sem_t s;
Sem_init(&s, 0, 0);

void *child(void *arg) {
    printf("child\n");
    post(&s); // child is done
    return NULL;
}

int main(void) {
    pthread_t c;
    pthread_create(&c, NULL, child, NULL);
    wait(&s); // wait for child
    printf("parent\n");
    return 0;
}

若 child 先执行 post(),value 从 0 变为 1,parent 随后 wait() 直接消费这个许可;若 parent 先执行 wait(),它会阻塞,直到 child 执行 post()。两种顺序都满足 child 先于 parent 输出。

31.4 The Producer/Consumer(Bounded Buffer)Problem:Figure 31.9–31.12

多 semaphore 协议的关键不是“所有对象都加锁”,而是严格维持每个 semaphore 所代表的不变量。一个常见的 bounded-buffer 版本如下:

c
sem_t empty, full;
Sem_init(&empty, 0, MAX); // MAX empty slots
Sem_init(&full,  0, 0);   // no full slots

void *producer(void *arg) {
    for (;;) {
        int item = produce_item();
        wait(&empty);
        put(item);
        post(&full);
    }
}

void *consumer(void *arg) {
    for (;;) {
        wait(&full);
        int item = get();
        post(&empty);
        consume_item(item);
    }
}

如果还需要保护环形队列本身,应使用 mutex,但顺序必须正确。下面的顺序会死锁:producer 先拿 mutex,随后等待 empty;当 buffer 已满时 producer 持有 mutex 阻塞,而 consumer 又需要同一个 mutex 才能取出 item、释放一个 empty 许可。

c
// Figure 31.11: incorrect ordering
wait(&mutex);
wait(&empty); // may block while holding mutex
put(item);
post(&mutex);
post(&full);

正确的顺序是先等待资源许可,再进入队列的 critical section;consumer 同理:

c
// Figure 31.12: correct ordering
// producer
wait(&empty);
wait(&mutex);
put(item);
post(&mutex);
post(&full);

// consumer
wait(&full);
wait(&mutex);
item = get();
post(&mutex);
post(&empty);

这正是 semaphore 协议中“等待时不要持有别人释放资源所需的 mutex”的一般性规则。

31.5 Reader-Writer Locks:Figure 31.13

c
typedef struct _rwlock_t {
    sem_t lock;       // protects the reader count
    sem_t writelock;  // one writer or many readers
    int   readers;
} rwlock_t;

void rwlock_acquire_read(rwlock_t *rw) {
    wait(&rw->lock);
    rw->readers++;
    if (rw->readers == 1)
        wait(&rw->writelock);
    post(&rw->lock);
}

void rwlock_release_read(rwlock_t *rw) {
    wait(&rw->lock);
    rw->readers--;
    if (rw->readers == 0)
        post(&rw->writelock);
    post(&rw->lock);
}

writer 直接 wait(&writelock),完成后 post(&writelock)。这个 reader-preference 方案允许多个 readers 并行,但持续到达的 readers 可能让 writer starvation。

Tip:Simple and Dumb Can Be Better(Hill’s Law)

在并发协议中,一个简单、容易审查的方案通常比一个更聪明但难以证明的方案更可靠。不要为了追求极限性能,过早引入无法清楚说明不变量的复杂机制。

31.6 The Dining Philosophers:Figure 31.14–31.16

五位 philosophers 围桌而坐,每人需要同时拿到左右两把 forks 才能吃饭。最直接的方案可能形成环形等待:

c
void get_forks(int p) {
    wait(&forks[p]);
    wait(&forks[(p + 1) % 5]); // can create circular wait
}

void put_forks(int p) {
    post(&forks[p]);
    post(&forks[(p + 1) % 5]);
}

一种简单修复是让最后一位 philosopher 反向获取 forks,从而破坏 circular wait:

c
void get_forks(int p) {
    if (p == 4) {
        wait(&forks[(p + 1) % 5]);
        wait(&forks[p]);
    } else {
        wait(&forks[p]);
        wait(&forks[(p + 1) % 5]);
    }
}

这只说明如何消除 deadlock;是否 starvation-free 还需要额外的 fairness 假设或调度协议。

31.7 Thread Throttling 与 31.8 How To Implement Semaphores:Figure 31.17

教材还给出一种用 lock 与 condition variable 实现的 semaphore,称为 Zemaphore:

c
typedef struct __Zem_t {
    int value;
    pthread_cond_t cond;
    pthread_mutex_t lock;
} Zem_t;

void Zem_init(Zem_t *z, int value) {
    z->value = value;
    pthread_cond_init(&z->cond, NULL);
    pthread_mutex_init(&z->lock, NULL);
}

void Zem_wait(Zem_t *z) {
    pthread_mutex_lock(&z->lock);
    while (z->value <= 0)
        pthread_cond_wait(&z->cond, &z->lock);
    z->value--;
    pthread_mutex_unlock(&z->lock);
}

void Zem_post(Zem_t *z) {
    pthread_mutex_lock(&z->lock);
    z->value++;
    pthread_cond_signal(&z->cond);
    pthread_mutex_unlock(&z->lock);
}

这个实现的 value 不会降到 0 以下;它与 Dijkstra 抽象实现中允许负值来记录等待者数量的方式不同,但行为上仍可提供相同的许可语义。教材指出,这种“value 不为负”的形式也更接近当前 Linux semaphore 的实现方式。

Generalization 的警告

semaphore 很强大,甚至可以只用 semaphore 来实现 lock 与 condition variable;不过从 semaphore 反向构造 condition variable 往往更难写对。应先写清楚 predicate、ownership、等待条件和唤醒条件,再选择 primitive。

Tip:Be Careful with Generalization

不要轻率地 generalize;Lampson 的表达是:“Don’t generalize; generalizations are generally wrong。”通用性只有在保持语义清晰、可验证时才真正有价值。

31.9 Summary:源文档收束

semaphore 是表达 concurrent program 同步的强大 primitive,可以代替 locks 与 condition variables。使用时必须根据 resource、ordering、ownership 和 fairness 明确初始化值与 wait/post 配对;从 semaphore 构造 condition variable 则比表面上更难。

源文档核对记录

  • 官方源文档:threads-sema.pdf,Version 1.10,共 20 页。
  • 已核对源章节:31.1–31.9。
  • 已核对图件:Figure 31.1–31.17;其中 Figure 31.4、31.5、31.7、31.8 的执行轨迹以表格保留,代码图以 code block 保留。
  • 原文没有需要单独下载的 raster image;Figure 31.14 的哲学家/叉子关系按语义保留在代码和说明中。

References(按官方 threads-sema.pdf)

  • [B04] Andrew D. Birrell, Implementing Condition Variables with Semaphores。
  • [CB08] Bryan Cantrill and Jeff Bonwick, Real-world Concurrency。
  • [CHP71] Courtois, Heymans, and Parnas, Concurrent Control with Readers and Writers。
  • [D59] Edsger W. Dijkstra, A Note on Two Problems in Connexion with Graphs。
  • [D68a] Edsger W. Dijkstra, Goto Statement Considered Harmful。
  • [D68b] Edsger W. Dijkstra, The Structure of the “THE” Multiprogramming System。
  • [D72] Edsger W. Dijkstra, Information Streams Sharing a Finite Buffer。
  • [D08] Allen B. Downey, The Little Book of Semaphores。
  • [D71] Edsger W. Dijkstra, Hierarchical Ordering of Sequential Processes。
  • [GR92] Jim Gray and Andreas Reuter, Transaction Processing: Concepts and Techniques。
  • [H87] Mark D. Hill, A Case for Direct-Mapped Caches。
  • [L83] Butler W. Lampson, Hints for Computer System Design。
  • [T99] Linus Torvalds, “Re: NT kernel guy playing with Linux”。
← 返回列表
← 上一篇 OSTEP:Condition Variables 下一篇 → OSTEP:Common Concurrency Problems

评论 (0)

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