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

OSTEP:Condition Variables

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

OSTEP:Condition Variables

本篇对应 OSTEP Version 1.10 的 “Condition Variables”。condition variable 让 thread 在 predicate 不满足时 sleep,并在共享状态改变后被 signal,而不是 busy-wait。

类型与定位

  • 笔记类型:深度分析
  • 翻译基准:官方 threads-cv.pdf,Version 1.10。
  • 图件说明:原文的 join、producer/consumer、wait/signal 时序和代码 listing 按原位置保留为代码块、表格和 Mermaid;没有独立 raster image。

TL;DR

  • condition variable 是等待队列,不是 condition 本身;真正的状态必须由 shared variable 表示。
  • wait 必须在持有 mutex 时调用,并原子地释放 mutex、睡眠、醒来后重新获得 mutex。
  • 等待 predicate 时使用 while 而不是 if,醒来后必须重新检查状态。
  • signal/broadcast 用于通知等待者;通常在持有同一 mutex 时修改状态并 signal。
  • bounded-buffer 的 not-empty 与 not-full 是 condition-variable 的经典应用。

目录

章节内容
为什么需要 condition variablespin 的问题
定义与基本接口wait/signal 与 mutex
Join 示例parent/child ordering
Producer/consumerbounded buffer
常见错误lost wakeup 与错误 predicate
使用规则while、锁与通知

为什么需要 condition variable

parent thread 需要等待 child 完成时,直接检查共享变量会 busy-wait:

c
volatile int done = 0;

while (done == 0)
    ;  // spin,浪费 CPU

我们希望 parent 在 child 完成前睡眠,完成后再被唤醒。condition variable 提供了一个显式等待队列,等待者加入队列,改变状态的 thread 负责 signal。

定义与基本接口

POSIX 接口是:

c
pthread_cond_wait(pthread_cond_t *c, pthread_mutex_t *m);
pthread_cond_signal(pthread_cond_t *c);

wait 假定 caller 已持有 mutex,并执行一个不可分割的动作:释放 mutex、把 caller 放入睡眠队列、睡眠;醒来后重新获得 mutex,再返回。这个原子性避免了“检查完状态但还没睡着就错过 signal”的 race。

condition variable 不是状态存储。状态由 predicate/shared variable 保存,例如 done、count、empty/full;signal 只是提示等待者重新检查 predicate。

Join 示例

c
int done = 0;
pthread_mutex_t m = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t c = PTHREAD_COND_INITIALIZER;

void thr_exit() {
    Pthread_mutex_lock(&m);
    done = 1;
    Pthread_cond_signal(&c);
    Pthread_mutex_unlock(&m);
}

void thr_join() {
    Pthread_mutex_lock(&m);
    while (done == 0)
        Pthread_cond_wait(&c, &m);
    Pthread_mutex_unlock(&m);
}

parent 和 child 的两种顺序都必须正确:

顺序结果
parent 先 waitparent 释放 lock 并睡眠,child 设置 done、signal,parent 醒来
child 先完成child 设置 done 后 signal;parent 随后看到 done=1,不会睡眠

如果没有 done 这样的 state variable,child 先 signal 时没有等待者,signal 会丢失,parent 之后可能永久睡眠。锁也不能省略:parent 检查 done 和进入睡眠之间若被 interrupt,child 可能恰好完成并 signal,造成 lost wakeup。

Producer/consumer

bounded buffer 中,producer 放入 item,consumer 取出 item。buffer 满时 producer 必须等待,buffer 空时 consumer 必须等待。至少需要两个 predicate:empty/not_empty 与 full/not_full。

mermaid
flowchart TD
  A[Producer] --> B{buffer full?}
  B -->|yes| C[wait not_full]
  C --> B
  B -->|no| D[put item]
  D --> E[signal not_empty]
  F[Consumer] --> G{buffer empty?}
  G -->|yes| H[wait not_empty]
  H --> G
  G -->|no| I[get item]
  I --> J[signal not_full]

典型模式是:持锁检查 predicate;不满足时在 while 中 wait;满足时修改 buffer;signal 可能因此被唤醒的另一类 waiter;最后释放 lock。

常见错误

用 if 而不是 while

c
if (count == 0)
    pthread_cond_wait(&not_empty, &lock);
item = get();

醒来后 predicate 可能已被其他 thread 改变;也可能存在 spurious wakeup。必须重新持锁检查:

c
while (count == 0)
    pthread_cond_wait(&not_empty, &lock);
item = get();

不保护 predicate

若 signal 与 predicate update 不在同一同步协议中,检查和睡眠之间就可能产生 race。共享状态的读写、wait 和相应 signal 应使用同一 mutex。

错误使用 signal/broadcast

signal 通常唤醒一个等待者,broadcast 唤醒所有等待者。若多个等待者都可能因状态改变而继续,就使用 broadcast;但所有醒来的 threads 都要重新检查 predicate,且会增加 contention。

使用规则

  • condition variable 与 predicate 配套设计;
  • wait 前持有保护 predicate 的 mutex;
  • 用 while 循环而不是 if;
  • 状态改变后再 signal;
  • 通常持锁修改状态并 signal,完成后 unlock;
  • 设计清楚 empty、full、done 等状态的不变量。

源文档逐段补充

Join 的 lost-wakeup 反例

condition variable 是一个显式等待队列,但它本身不保存“事情已经完成”的事实。若 child 只负责 signal:

c
void thr_exit() {
    Pthread_mutex_lock(&m);
    Pthread_cond_signal(&c);
    Pthread_mutex_unlock(&m);
}

void thr_join() {
    Pthread_mutex_lock(&m);
    Pthread_cond_wait(&c, &m);
    Pthread_mutex_unlock(&m);
}

child 可能在 parent 进入 wait 前就完成并 signal;因为当时没有 waiter,signal 不会留下记录,parent 随后会永久睡眠。因此必须有 done 这样的 state variable,等待方检查事实而不是只等待一个瞬时 notification。

即使有 done,也不能去掉 mutex:parent 检查 done == 0 后、实际进入 wait 前可能被 interrupt;child 在这段窗口内把 done 设为 1 并 signal,仍会造成 lost wakeup。pthread_cond_wait() 将“释放 mutex、加入 wait queue、睡眠”作为一个原子协议,正是为消除这个窗口。

Signal 的基本纪律

修改 predicate 的 thread 应在持有保护该 predicate 的 mutex 时 signal:

c
Pthread_mutex_lock(&lock);
ready = 1;
Pthread_cond_signal(&cond);
Pthread_mutex_unlock(&lock);

在所有代码中保持这一约定最简单,也最不容易引入 race。wait 必须持锁是 API 的硬性语义;signal 持锁在某些实现中并非绝对必要,但通常应作为统一规则。

Producer/consumer 的场景

bounded buffer 同时服务于多种系统结构:web server 的 producer 将 HTTP request 放进 work queue,consumer worker 取出并处理;UNIX pipeline grep foo file.txt | wc -l 中,grep 是 producer,wc 是 consumer,kernel pipe 是中间的 bounded buffer。

单 slot buffer 的不变量是:count == 0 时 producer 才能 put(),count == 1 时 consumer 才能 get():

c
int buffer;
int count = 0;

void put(int value) {
    assert(count == 0);
    count = 1;
    buffer = value;
}

int get() {
    assert(count == 1);
    count = 0;
    return buffer;
}

一个 condition variable 加 if 的失败版本

最初的实现让 producer 在 buffer full 时等待,consumer 在 buffer empty 时等待,但二者共用一个 condition variable,并且使用 if 而非 while。当有两个 consumer 时,producer signal 唤醒 consumer Tc1 后,Tc2 可能在 Tc1 重新获得 mutex 前先消费唯一的 item;Tc1 醒来后直接执行 get(),却发现 buffer 已经空了。

这揭示了 Mesa semantics:signal 只把 waiter 移回 ready queue,表示“状态可能发生了变化”,并不保证被唤醒的 thread 立刻运行,也不保证 predicate 在它重新拿到 lock 时仍然为真。Hoare semantics 会保证被 signal 的 thread 立即运行,但实现更复杂;几乎所有实际系统采用 Mesa semantics。

因此修复第一处 bug 的规则是:醒来后必须重新检查 predicate。

c
Pthread_mutex_lock(&mutex);
while (count == 0)
    Pthread_cond_wait(&cond, &mutex);
int tmp = get();
Pthread_cond_signal(&cond);
Pthread_mutex_unlock(&mutex);

一个 condition variable 加 while 仍然失败

while 解决了错误消费 empty buffer 的问题,但 single condition variable 仍可能唤醒错误类型的 waiter。假设两个 consumer 都在等待 empty,producer 放入 item 并唤醒 Tc1;producer 随后因 buffer full 也进入同一个等待队列。Tc1 消费 item 后 signal,可能唤醒另一个 consumer Tc2,而不是应该被唤醒的 producer。Tc2 发现 buffer empty,再次 sleep,producer 仍睡眠,所有 thread 最终都可能睡着。

问题不在 signal 是否存在,而在一个 condition queue 混合了两个不同 predicate:buffer-not-empty 和 buffer-not-full。consumer 应只唤醒 producer,producer 应只唤醒 consumer。

两个 condition variable 的正确版本

c
cond_t empty, fill;
mutex_t mutex;

void *producer(void *arg) {
    for (int i = 0; i < loops; i++) {
        Pthread_mutex_lock(&mutex);
        while (count == MAX)
            Pthread_cond_wait(&empty, &mutex);
        put(i);
        Pthread_cond_signal(&fill);
        Pthread_mutex_unlock(&mutex);
    }
}

void *consumer(void *arg) {
    for (int i = 0; i < loops; i++) {
        Pthread_mutex_lock(&mutex);
        while (count == 0)
            Pthread_cond_wait(&fill, &mutex);
        int tmp = get();
        Pthread_cond_signal(&empty);
        Pthread_mutex_unlock(&mutex);
        printf("%d\\n", tmp);
    }
}

producer 在 empty 上等待、在 fill 上 signal;consumer 在 fill 上等待、在 empty 上 signal。增加 ring buffer 后,fill_ptr、use_ptr 和 count 共同维护队列状态:只要 count < MAX,producer 可以继续生产;只要 count > 0,consumer 可以继续消费。更大的 buffer 还减少 context switch,并允许多个 producer/consumer 在不必要睡眠前连续完成多次操作。

Covering condition

有些 predicate 很难通过 condition variable 精确区分。例如 memory allocator 中,多个 thread 可能分别请求 100 bytes 与 10 bytes;当前只有 50 bytes 可用时,只应唤醒后者。如果 signal() 恰好唤醒等待 100 bytes 的 thread,它会重新 sleep,而真正能运行的 thread 仍未被唤醒。

c
while (bytesLeft < size)
    Pthread_cond_wait(&c, &m);

这种情况下可使用 pthread_cond_broadcast() 唤醒所有 waiter;每个 thread 持锁重新检查自己的 predicate,满足的继续执行,不满足的立即回睡。Lampson 与 Redell 将这种保守地覆盖所有可能唤醒对象的条件称为 covering condition。代价是可能产生 thundering herd:许多不满足条件的 thread 被无谓唤醒。

如果一个程序只有把 signal 改成 broadcast 才能工作,通常说明 condition 设计或 predicate 分组存在 bug;但在 allocator 这类无法精确知道应唤醒谁的场景中,broadcast 可能是最简单、正确的选择。

Condition variable 的不变量

设计 CV 协议时可以用以下不变量检查实现:

对象不变量
donechild 完成后永久为 1;parent 只在 done == 1 后继续
单 slot buffercount 只能为 0 或 1
ring buffer0 <= count <= MAX;fill_ptr/use_ptr 按 modulo 前进
emptyproducer 只在 buffer 未满时被唤醒并继续
fillconsumer 只在 buffer 非空时被唤醒并继续

signal 是提示,不是状态;mutex 保护状态,while 重新验证状态,三者缺一不可。

官方 Code Homework:Producer/Consumer Queue

原文的 Code Homework 使用真实的 lock 与 condition variable 实现,比较不同 producer/consumer 数量、buffer size、sleep location 和 signaling 方案。具体 build/run 方法以 homework download 中的 README 为准。

  1. 阅读 main-two-cvs-while.c(working solution),先预测它的运行行为。

  2. 使用一个 producer、一个 consumer,生产少量 item;从 buffer size 为 1 开始逐步增大,观察行为是否变化。结合 -m 10、-l 100,以及 consumer 在 c3 处暂停的 -C 0,0,0,0,0,0,1,预测不同 buffer size 下的 num_full。

  3. 如果条件允许,在不同系统(例如 macOS 与 Linux)上运行,比较行为是否不同,并说明可能原因。

  4. 预测以下配置的运行时间:一个 producer、三个 consumers、单 slot buffer,每个 consumer 在 c3 处暂停一秒:

    ./main-two-cvs-while -p 1 -c 3 -m 1 -C 0,0,0,1,0,0,0:0,0,0,1,0,0,0:0,0,0,1,0,0,0 -l 10 -v -t
    
  5. 将 buffer size 改为 3(-m 3),判断总时间是否变化,并解释原因。

  6. 将 sleep 从 c3 移到 c6,用单 slot buffer 运行:

    ./main-two-cvs-while -p 1 -c 3 -m 1 -C 0,0,0,0,0,0,1:0,0,0,0,0,0,1:0,0,0,0,0,0,1 -l 10 -v -t
    

    预测这时的总时间。

  7. 再将 buffer size 改为 3,预测总时间,并与第 6 题比较。

  8. 阅读 main-one-cv-while.c。在一个 producer、一个 consumer、buffer size 为 1 的条件下,构造一个 sleep string 使该实现出问题。

  9. 将 consumer 数量改为 2,分别为 producer 和 consumers 构造 sleep strings,触发 single-CV 实现的问题。

  10. 阅读 main-two-cvs-if.c,尝试让它出错;分别考虑只有一个 consumer 和有多个 consumers 的情况。

这些实验要把“能运行”与“协议正确”区分开:sleep string 只是帮助构造特定 interleaving,buffer size 既影响可获得的 concurrency,也会改变 producer/consumer 因 predicate 不满足而阻塞的频率。

本章小结

condition variable 是建立在 shared state 与 mutex 之上的等待队列,而不是独立保存状态的 notification。正确协议可以概括为:持有 mutex,使用 while 检查 predicate;predicate 不满足时调用 wait;状态改变后在适当的 condition 上 signal 或 broadcast;最后释放 mutex。join、bounded buffer 和 covering condition 展示了这一模式在不同问题中的应用。

与已有笔记的关系

参考资料

原文逐段补充

锁并不是构建 concurrent program 所需的唯一 primitive。很多时候,thread 需要先检查某个 condition 是否为真,才能继续执行;例如 parent 要等待 child 完成,这通常称为 join()。

30.1 Definition and Routines:Figure 30.1–30.5

最初的 parent/child 示例:

c
void *child(void *arg) {
    printf("child\n");
    // XXX how to indicate we are done?
    return NULL;
}

int main(int argc, char *argv[]) {
    printf("parent: begin\n");
    pthread_t c;
    Pthread_create(&c, NULL, child, NULL);
    // XXX how to wait for child?
    printf("parent: end\n");
    return 0;
}

期望输出为 parent: begin、child、parent: end。只用 shared done flag 的版本会让 parent 一直 spin,浪费 CPU。对此,本章的核心问题是:

CRUX:HOW TO WAIT FOR A CONDITION

多线程 program 中,thread 常常需要等待某个 condition 成立后才能继续。一直 spin 既低效,在某些情况下还不正确;那么 thread 应该如何等待 condition?

condition variable 是一个显式 queue:当 execution state 不满足时,thread 将自己放入 queue;另一个 thread 改变 state 后,通过 signal() 唤醒一个或多个 waiter。这个思想可追溯到 Dijkstra 的 “private semaphores” [D68],后来 Hoare 在 monitor 工作中称其为 condition variable [H74]。

正确的 join 版本(Figure 30.3):

c
int done = 0;
pthread_mutex_t m = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t c = PTHREAD_COND_INITIALIZER;

void thr_exit() {
    Pthread_mutex_lock(&m);
    done = 1;
    Pthread_cond_signal(&c);
    Pthread_mutex_unlock(&m);
}

void *child(void *arg) {
    printf("child\n");
    thr_exit();
    return NULL;
}

void thr_join() {
    Pthread_mutex_lock(&m);
    while (done == 0)
        Pthread_cond_wait(&c, &m);
    Pthread_mutex_unlock(&m);
}

如果 parent 先运行,它看到 done == 0,wait 会原子地释放 mutex 并睡眠;child 随后设置 done、signal,parent 醒来时重新持有 mutex。如果 child 先运行,done 已为 1,parent 后续直接通过 while 检查,不会睡眠。因此 state variable 记录事实,condition variable 只负责等待与唤醒。

没有 state variable 的版本(Figure 30.4)是错误的:child 可能在 parent wait 前 signal,而没有 waiter 接收该 signal,parent 随后永久睡眠。没有 mutex 的版本(Figure 30.5)也错误:parent 检查到 done == 0 后、调用 wait 前被 interrupt,child 设置 done 并 signal,parent 恢复后仍会睡眠。这正是 wait 必须把“释放 mutex、入队、睡眠”作为原子协议的原因。

Figure 30.4 的原文错误版本(省略 state variable):

c
void thr_exit() {
    Pthread_mutex_lock(&m);
    Pthread_cond_signal(&c);
    Pthread_mutex_unlock(&m);
}

void thr_join() {
    Pthread_mutex_lock(&m);
    Pthread_cond_wait(&c, &m);
    Pthread_mutex_unlock(&m);
}

Figure 30.5 的原文错误版本(省略 mutex;这里只是为了展示 race,真实的 pthread_cond_wait() 接口需要 mutex):

c
void thr_exit() {
    done = 1;
    Pthread_cond_signal(&c);
}

void thr_join() {
    if (done == 0)
        Pthread_cond_wait(&c);
}

TIP:ALWAYS HOLD THE LOCK WHILE SIGNALING

signal 时持有 lock 在所有场景下未必严格必要,但通常是最简单、最安全的规则。wait 时持有 lock 则不是 tip,而是 API semantics 的要求:wait 假设 lock 已持有,睡眠时释放它,返回前重新获得它。

30.2 The Producer/Consumer(Bounded Buffer)Problem:Figure 30.6–30.10

单 slot buffer 的 put()/get():

c
int buffer;
int count = 0; // initially empty

void put(int value) {
    assert(count == 0);
    count = 1;
    buffer = value;
}

int get() {
    assert(count == 1);
    count = 0;
    return buffer;
}

producer 反复 put,consumer 反复 get:

c
void *producer(void *arg) {
    int loops = (int) arg;
    for (int i = 0; i < loops; i++)
        put(i);
}

void *consumer(void *arg) {
    while (1) {
        int tmp = get();
        printf("%d\n", tmp);
    }
}

Producer/consumer(也称 bounded-buffer)最早由 Dijkstra 提出 [D72]。它出现在 web server 的 request queue 中,也出现在 grep foo file.txt | wc -l 中:grep 是 producer,wc 是 consumer,kernel pipe 是中间的 bounded buffer。

single condition variable + if 的原文代码(Figure 30.8)如下:

c
int loops;
cond_t cond;
mutex_t mutex;

void *producer(void *arg) {
    for (int i = 0; i < loops; i++) {
        Pthread_mutex_lock(&mutex);       // p1
        if (count == 1)                   // p2
            Pthread_cond_wait(&cond, &mutex); // p3
        put(i);                            // p4
        Pthread_cond_signal(&cond);       // p5
        Pthread_mutex_unlock(&mutex);     // p6
    }
}

void *consumer(void *arg) {
    for (int i = 0; i < loops; i++) {
        Pthread_mutex_lock(&mutex);       // c1
        if (count == 0)                   // c2
            Pthread_cond_wait(&cond, &mutex); // c3
        int tmp = get();                  // c4
        Pthread_cond_signal(&cond);       // c5
        Pthread_mutex_unlock(&mutex);     // c6
        printf("%d\n", tmp);
    }
}

两个 consumer 时,producer signal 只能把 Tc1 从 sleeping 移到 ready;在 Tc1 真正运行前,Tc2 可能取得 mutex 并消费唯一 item。Tc1 醒来后不重新检查,直接 get() 空 buffer,assertion 触发。Figure 30.9 的核心 trace 是:Tc1 sleep → producer put/signal → Tc1 ready → producer 因 full sleep → Tc2 抢先 get → Tc1 恢复后发现“没有 data”。

Figure 30.9 的完整状态 trace(Run、Ready、Sleep 分别表示 running、ready queue 和 sleeping):

步骤Tc1Tc2Tpcount说明
1RunReadyReady0Tc1 获取 mutex
2RunReadyReady0Tc1 检查 count == 0
3SleepReadyReady0Tc1 没有 data,进入 sleep
4SleepReadyRun0Tp 获取 mutex
5SleepReadyRun0Tp 检查 buffer 未满
6SleepReadyRun1Tp put;buffer 现在 full
7ReadyReadyRun1Tp signal;Tc1 被唤醒但仅进入 ready
8ReadyReadyRun1Tp release mutex
9ReadyReadyRun1Tp 再次运行并检查 buffer
10ReadyReadySleep1Tp 发现 full,重新 sleep
11ReadyRunSleep1Tc2 抢先获取 mutex
12ReadyRunSleep1Tc2 检查到有 data
13ReadyRunSleep0Tc2 get;唯一 item 被取走
14ReadyRunReady0Tc2 signal;Tp 被唤醒
15RunReadyReady0Tc1 恢复,直接执行 get;没有 data

这体现 Mesa semantics:signal 只表示 state 可能发生变化,只把 waiter 放回 ready queue;不保证它立即运行,也不保证 predicate 仍为真。Hoare semantics 会让被 signal 的 thread 立即运行,但实现更复杂;几乎所有实际 system 都采用 Mesa semantics。因此 Figure 30.10 将 producer 与 consumer 的 if 都改为 while。

然而 single CV + while 仍可能失败:两个 consumer 都睡眠后,producer put 一个 item 并唤醒 Tc1,随后 producer 因 buffer full 也睡眠。Tc1 消费 item 后 signal,可能错误地唤醒 Tc2 而不是 producer;Tc2 发现 buffer empty 再次睡眠,最后所有 threads 都睡着。问题是同一个 condition queue 混合了“buffer not empty”和“buffer not full”两个不同 predicate。正确方案(Figure 30.12)使用 empty 与 fill 两个 CV:producer 在 empty 上等待、signal fill;consumer 在 fill 上等待、signal empty。

30.3 More Concurrent Data Structures:Figure 30.11–30.14

正确的单 slot 版本:

c
int loops;
cond_t empty, fill;
mutex_t mutex;

void *producer(void *arg) {
    for (int i = 0; i < loops; i++) {
        Pthread_mutex_lock(&mutex);
        while (count == 1)
            Pthread_cond_wait(&empty, &mutex);
        put(i);
        Pthread_cond_signal(&fill);
        Pthread_mutex_unlock(&mutex);
    }
}

void *consumer(void *arg) {
    for (int i = 0; i < loops; i++) {
        Pthread_mutex_lock(&mutex);
        while (count == 0)
            Pthread_cond_wait(&fill, &mutex);
        int tmp = get();
        Pthread_cond_signal(&empty);
        Pthread_mutex_unlock(&mutex);
        printf("%d\n", tmp);
    }
}

多 slot buffer 的 put()/get() 使用 fill_ptr、use_ptr 与 count:

c
int buffer[MAX];
int fill_ptr = 0;
int use_ptr = 0;
int count = 0;

void put(int value) {
    buffer[fill_ptr] = value;
    fill_ptr = (fill_ptr + 1) % MAX;
    count++;
}

int get() {
    int tmp = buffer[use_ptr];
    use_ptr = (use_ptr + 1) % MAX;
    count--;
    return tmp;
}

producer 只在 count == MAX 时睡眠,consumer 只在 count == 0 时睡眠。更大的 buffer 可以让多个 values 在睡眠前被生产或消费,减少 context switches,并提高多个 producers/consumers 的 concurrency。

TIP:USE WHILE (NOT IF) FOR CONDITIONS

检查 condition 时,while 总是安全;if 是否安全取决于 signaling semantics。while 还可以处理 spurious wakeup:某些 thread package 可能因 signal/wakeup implementation 的细节唤醒多于一个 thread,因此必须重新检查 predicate。

30.4 Covering Conditions:Figure 30.15

memory allocator 可能有多个不同大小的等待请求:

c
int bytesLeft = MAX_HEAP_SIZE;
cond_t c;
mutex_t m;

void *allocate(int size) {
    Pthread_mutex_lock(&m);
    while (bytesLeft < size)
        Pthread_cond_wait(&c, &m);
    void *ptr = ...; // get mem from heap
    bytesLeft -= size;
    Pthread_mutex_unlock(&m);
    return ptr;
}

void free(void *ptr, int size) {
    Pthread_mutex_lock(&m);
    bytesLeft += size;
    Pthread_cond_broadcast(&c); // wake all possible waiters
    Pthread_mutex_unlock(&m);
}

假设 Ta 等待 100 bytes,Tb 只等待 10 bytes,当前 free bytes 为 0;Tc free 50 bytes 时,signal() 可能只唤醒 Ta,Ta 发现仍不足 100 bytes 后继续睡眠,Tb 却没被唤醒。broadcast() 保守地唤醒所有 waiters,每个 thread 重新检查自己的 predicate;满足条件的继续,不满足的立即睡回去。这叫 covering condition [LR80],代价是可能无谓唤醒很多 threads。若普通程序只有把 signal 改为 broadcast 才工作,往往说明 CV/predicate 设计有 bug;allocator 这种无法精确知道应唤醒谁的场景则是合理例外。

30.5 Summary:源文档收束

condition variable 通过等待队列让 thread 在 predicate 不满足时睡眠;正确使用的关键是以 state variable 表示事实、在持有 mutex 时 wait/signal、用 while 重新检查 predicate,并为不同 predicate 使用不同的 condition variables。bounded buffer 展示了从 single CV 到 two-CV、多 slot buffer 和 covering condition 的演进。

源文档核对记录

  • 官方源文档:threads-cv.pdf,Version 1.10,共 19 页。
  • 已核对源章节:30.1–30.5。
  • 已核对图件:Figure 30.1–30.15;错误代码、完整线程状态 trace 和多 slot buffer 均按原文位置保留。
  • 原文没有需要单独下载的 raster image;Figure 30.9 的状态图已转换为表格,保留线程状态、count 与注释列。

References

  • [D68] Edsger W. Dijkstra,《Cooperating sequential processes》,1968。
  • [D72] E. W. Dijkstra,《Information Streams Sharing a Finite Buffer》,Information Processing Letters,1,1972:producer/consumer problem 的经典来源。
  • [D01] E. W. Dijkstra,《My recollections of operating system design》,2001:关于 interrupts、stack 等基础概念的回忆。
  • [H74] C. A. R. Hoare,《Monitors: An Operating System Structuring Concept》,Communications of the ACM,17(10),1974。
  • [L11] 《Pthread cond signal Man Page》,2011:spurious wakeup 的例子。
  • [LR80] B. W. Lampson、D. R. Redell,《Experience with Processes and Monitors in Mesa》,Communications of the ACM,23(2),1980:Mesa semantics 与 covering condition。
  • [O49] George Orwell,《Nineteen Eighty-Four》,1949:原文小结中的文学引用。
← 返回列表
← 上一篇 OSTEP:Lock-based Concurrent Data Structures 下一篇 → OSTEP:Semaphores

评论 (0)

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