OSTEP:Event-based Concurrency
OSTEP:Event-based Concurrency
本篇对应 OSTEP 的 “Event-based Concurrency”。另一种并发模型不为每个 task 创建 blocking thread,而是使用 event loop、non-blocking I/O 与 callback 管理大量并发活动。
类型与定位
- 笔记类型:深度分析
- 翻译基准:官方 threads-events.pdf。
- 图件说明:原文的 event loop、state machine 与 blocking/non-blocking 对比按原位置改写为 Mermaid 和代码块;没有独立 raster image。
TL;DR
- event-based concurrency 用一个 event loop 从 ready queue 取事件并执行 handler。
- handler 必须短小且 non-blocking,否则会阻塞整个 event loop。
- non-blocking API 返回 EAGAIN 等状态,程序把未完成工作保存为 state,待后续 event 到来后继续。
- 优点是较少 thread、较低 context-switch 与 synchronization 成本;缺点是编程模型复杂,阻塞操作和多 CPU 利用需要额外处理。
- asynchronous I/O、readiness notification 与 state machine 是 event-based system 的核心。
目录
| 章节 | 内容 |
|---|---|
| 基本模型 | event loop 与 handler |
| 非阻塞 I/O | readiness 与 EAGAIN |
| State machine | 保存未完成工作 |
| 优点与局限 | threads 与 events 对比 |
| 多核与混合模型 | event loop 的扩展 |
基本模型
thread-based server 通常为每个 connection 创建 thread 或从 thread pool 取 worker;event-based server 则由一个 event loop 统一接收并分发事件:
flowchart TD
A[等待 I/O events] --> B[Event loop]
B --> C[取出 ready event]
C --> D[调用 handler]
D --> E[更新 state / 注册下一次 interest]
E --> A
event loop 本身串行执行 handler,因此同一 loop 中的 shared state 通常不需要 thread-level lock。代价是任何 handler 都不能长时间运行或阻塞,否则所有其他 connections 都无法推进。
非阻塞 I/O
blocking read 在数据未到达时会睡眠当前 thread;event-based system 使用 non-blocking descriptor:
int rc = read(fd, buffer, sizeof(buffer));
if (rc > 0) {
process_bytes(buffer, rc);
} else if (rc == -1 && errno == EAGAIN) {
// 当前没有数据,等待下一次 read-ready event
} else {
// EOF 或真正的 error
}
当 API 返回 EAGAIN 时,程序不能把它当作 fatal error,也不能立即 busy-wait;应保存 connection state,并向 event system 注册对 read/write readiness 的兴趣。select、poll、epoll、kqueue 等机制都可提供类似的 readiness notification,具体 API 取决于 OS。
State machine
blocking code 可以按自然控制流写成:
while (request_not_complete) {
read_request();
parse_request();
write_response();
}
event-based code 必须拆成多个状态,保存 partial request、buffer offset 和下一步操作:
stateDiagram-v2
[*] --> Reading
Reading --> Reading: read returns EAGAIN
Reading --> Parsing: request complete
Parsing --> Writing: response ready
Writing --> Writing: write returns EAGAIN
Writing --> Closed: response complete
Closed --> [*]
每次 handler 运行一小段后返回 event loop;下一次 readiness event 到来时,根据保存的 state 继续。这样把 blocking control flow 转换为显式 finite-state machine。
优点与局限
| 方面 | Event-based | Thread-based |
|---|---|---|
| 大量 connections | 少量 event-loop resources | 需要管理大量 threads 或 pool |
| context switch | 通常较少 | 可能较多 |
| shared state | 同一 loop 内较简单 | 需要 locks/同步 |
| 编程方式 | callback/state machine | 顺序 blocking code 更自然 |
| blocking 操作 | 必须特别避免 | 可阻塞当前 worker |
| 多 CPU | 需要多个 loops/worker | 可自然映射到 CPUs |
event-based 并不会自动让所有工作更快;它主要减少等待大量连接时的 per-thread 成本。CPU-bound handler 仍然需要拆分、移交 worker 或使用多 event loops。
多核与混合模型
单 event loop 只能同时在一个 CPU 上执行 handler。常见扩展是使用多个 event loops,每个 loop 绑定一个 CPU,或用 event loop 处理网络 readiness,再把 CPU-heavy 工作交给 thread pool:
flowchart LR
A[Network events] --> B[Event loop 0]
A --> C[Event loop 1]
B --> D[Worker pool]
C --> D
D --> E[完成事件 / response]
跨 loops 共享 data 时仍需要 synchronization;因此 event-based 只减少同一 loop 内的并发问题,不会消除系统级共享状态。
设计原则
- handler 必须短小、可重入且 non-blocking;
- 为每个 connection 定义清晰 state;
- 正确处理 partial read/write、EOF、EAGAIN 与 error;
- 对 slow client 设置 backpressure 和资源上限;
- 将 CPU-bound 与 blocking work 移出 event loop;
- 根据 workload 比较 event-based、thread pool 和混合模型。
源文档逐段补充
为什么采用 event-based concurrency
event-based concurrency 主要回应两个问题:multi-threaded application 中 lock、deadlock 等 correctness bug 难以处理;同时 programmer 几乎无法控制 OS scheduler 下一步运行哪个 thread,scheduler 在某些 workload 上可能做出不理想的选择。event loop 把一部分 scheduling control 交回 application。
while (1) {
events = getEvents();
for (e in events)
processEvent(e);
}
getEvents() 等待 ready event,processEvent() 是 event handler。handler 一次只处理一个 event,因此选择下一个 event 就等价于调度;在 single-CPU、single-loop 模型中,同一时刻没有其他 thread 插入,shared state 通常不需要 lock。
select() 与 poll() 的 readiness
select() 可以同时检查 descriptors 是否 ready for reading、writing,或存在 exception:
int select(int nfds,
fd_set *restrict readfds,
fd_set *restrict writefds,
fd_set *restrict errorfds,
struct timeval *restrict timeout);
readfds 让 server 发现新 packet 或可读数据,writefds 让 server 判断 outbound queue 是否有空间发送 response。timeout == NULL 会一直阻塞到 descriptor ready;timeout 为 0 则立即返回,可用于 polling。poll() 提供类似能力,具体选择取决于 platform 和 descriptor 数量。
典型 event loop 会先用 FD_ZERO() 清空集合,用 FD_SET() 注册关注的 descriptors,调用 select(),再用 FD_ISSET() 找出真正 ready 的 descriptor:
fd_set readFDs;
FD_ZERO(&readFDs);
for (int fd = minFD; fd < maxFD; fd++)
FD_SET(fd, &readFDs);
select(maxFD + 1, &readFDs, NULL, NULL, NULL);
for (int fd = minFD; fd < maxFD; fd++)
if (FD_ISSET(fd, &readFDs))
processFD(fd);
readiness API 只告诉程序“现在可以尝试某个 operation”,并不保证一次调用能够完成全部 read/write;因此 partial I/O、EOF、error 和下一次 interest 都必须保存在 connection state 中。
Blocking 与 non-blocking
blocking/synchronous interface 在返回前完成工作;non-blocking/asynchronous interface 启动工作后立即返回,让工作在后台继续。对于 event loop,任何会阻塞 caller 的 call 都可能阻塞所有 connections,因此必须避免 blocking handler。
例如,server 收到请求后要 open() 一个 file,再多次 read(),这些调用可能因为 metadata 或 data 不在 memory 中而触发 disk I/O。thread-based server 可以让当前 worker 睡眠、由其他 worker 继续服务;single event loop 没有其他 thread 可运行,整个 server 会停住。因此“不要在 event-based server 中 block”不是优化建议,而是模型的基本约束。
Asynchronous disk I/O
为处理 disk I/O,系统可以提供 asynchronous I/O。以 macOS 的 AIO interface 为例,应用先填充 control block:
struct aiocb {
int aio_fildes;
off_t aio_offset;
volatile void *aio_buf;
size_t aio_nbytes;
};
aio_read(&cb); // 发起请求,立即返回
aio_error(&cb); // 0: 完成;EINPROGRESS: 仍在进行
持续 polling 数十或数百个 outstanding I/O 并不理想;有些系统使用 UNIX signal 在 I/O 完成时通知 application,减少反复检查。若 platform 没有合适的 asynchronous disk I/O,常见替代方案是 hybrid:event loop 处理 network packet,thread pool 处理可能阻塞的 disk I/O。
Event-based state management
thread-based code 可以自然地写成:
int rc = read(fd, buffer, size);
rc = write(sd, buffer, size);
sd 等局部变量留在 thread stack 中,read 完成后自然可用。event-based code 中,read asynchronous 返回后 handler 已结束;下一次 completion event 到来时,程序必须知道应该把数据写到哪个 socket。这种手工保存“下一步继续执行所需的 stack state”的工作称为 manual stack management。
一种 continuation 方案是把 fd → sd 和其他未完成操作信息保存到 hash table;disk I/O 完成后,handler 根据 fd 查找 continuation,恢复下一步的 write。callback、future/promise 和显式 finite-state machine 都是这一思想的不同表达。
UNIX signals 作为异步通知
UNIX signal 可以在 process 正常执行时打断它,转而运行 signal handler,完成后再恢复原来的 execution。HUP、INT、SEGV 等 signal 各有语义;kernel 也可以发送 SIGSEGV 报告非法 memory access,若程序没有 handler,默认行为通常是终止 process。signal 可以作为 asynchronous I/O completion notification,但 handler 受限于 signal-safety,不能把它当作普通 callback 任意使用。
Event model 的剩余困难
- 多核:为了使用多个 CPU,需要并行运行多个 handler;一旦 handler 同时执行,critical section、lock 和 synchronization 问题重新出现。
- 隐式 blocking:event handler 即使不显式调用 blocking API,也可能因为 page fault 而阻塞整个 loop;paging 很难完全从 event model 中隔离。
- API 语义漂移:某个 routine 若从 non-blocking 改成 blocking,所有调用它的 handler 都必须拆分并重写;event code 对 API blocking semantics 极其敏感。
- I/O API 不统一:network readiness 常由
select()/poll()管理,而 disk asynchronous I/O 可能需要 AIO,二者很难完全用一个统一接口处理。
因此 event-based 与 thread-based 并无一个普适赢家:events 提供更强的调度控制和较低的 per-connection 成本,threads 保留自然的 sequential control flow 和更好的 blocking/I/O 隔离;现代系统通常根据 workload 采用其中一种或 hybrid。
官方 Code Homework:从 TCP Server 到 Event Loop
原文的 Code Homework 用一个逐步扩展的 server 练习 event-based programming:
- 编写一个能接受并服务 TCP connection 的简单 server,一次只服务一个 request;request 可以简单到返回当前时间。
- 加入
select(),让 server 接受多个 connections,并用 event loop 检查哪些 file descriptors 有数据,再读取和处理 request。仔细验证select()的 fd set 使用方式。 - 把 request 扩展成简单 web/file server:request 指定文件名,server 使用
open()、read()、close()读取文件并把内容返回 client。注意不要让这个实验 server 暴露出任意读取本机敏感文件的风险。 - 不再使用普通 synchronous I/O,改用本章介绍的 asynchronous I/O;记录把异步接口接入原有 event loop 的难点。
- 加入 signal handling。例如实现一个 user-level file cache,并让 signal handler 在收到指定 signal 时清空 cache。
- 设计实验判断 asynchronous event-based approach 是否值得:比较 throughput、latency、resource use、实现复杂度和 failure modes,而不是只比较一组 benchmark 数字。
本章小结
event-based concurrency 通过 event loop 把一部分 scheduling control 交回 application:每次只处理一个 ready event,single-loop/single-CPU 模型因此可以避免许多 thread-level lock 问题。select()/poll() 提供 readiness notification,non-blocking 与 asynchronous I/O 让 handler 能够尽快返回,continuation、callback 或 state machine 保存尚未完成的 stack state。
这种模型的关键约束是 不要 block。显式 blocking system call、page fault 等隐式阻塞都会停住整个 event loop;多核、disk I/O、API blocking semantics 的变化也会重新带来复杂性。threads、events 与 hybrid 并不存在普适赢家,应按 workload 和可维护性选择。
与已有笔记的关系
- OSTEP:并发导论:thread-based concurrency 与调度交错。
- OSTEP:Thread API:thread 创建与等待的接口。
- OSTEP:Condition Variables:blocking thread 的 sleep/wakeup 模型。
- OSTEP:IO Devices:device、interrupt 与 I/O path。
参考资料
原文逐段补充(Version 1.10)
本章 CRUX:如何在没有 threads 的情况下构建 concurrent server
event-based concurrency 最早广泛用于 GUI application 和部分 Internet server,后来也出现在 node.js 等 server-side framework 中。它针对两个问题:multi-threaded application 中 missing lock、deadlock 等 correctness bug 很难处理;同时 programmer 创建 threads 后,几乎无法控制 OS scheduler 在某一时刻选择谁运行。event loop 把一部分 scheduling control 交还给 application,并提出本章核心问题:如何在不使用 threads 的情况下构建 concurrent server,同时保留 concurrency control 并避开 multi-threaded application 的部分问题?
Figure 33.1:使用 select() 的完整示例
#include <stdio.h>
#include <stdlib.h>
#include <sys/time.h>
#include <sys/types.h>
#include <unistd.h>
int main(void) {
// open and set up a bunch of sockets (not shown)
while (1) {
fd_set readFDs;
FD_ZERO(&readFDs);
int fd;
for (fd = minFD; fd < maxFD; fd++)
FD_SET(fd, &readFDs);
int rc = select(maxFD + 1, &readFDs, NULL, NULL, NULL);
for (fd = minFD; fd < maxFD; fd++)
if (FD_ISSET(fd, &readFDs))
processFD(fd);
}
}
select() 检查 readfds、writefds 和 errorfds 中的 descriptor:前者表示可以读取(例如新 packet 已到达),后者表示可以写入(例如 outbound queue 不再满)。调用返回后,传入的 set 会被替换为 ready descriptor 的子集;返回值是所有 set 中 ready descriptor 的总数。nfds 表示检查 descriptor 0 到 nfds - 1。
timeout == NULL 会一直等待到至少一个 descriptor ready;将 timeout 设为零则会立即返回,可用于 polling。select() 与 poll() 提供相近的能力,但它们只告诉程序某个 operation 当前可以尝试,并不保证一次 read() 或 write() 就能完成全部数据,所以真实 server 仍需处理 partial I/O、EOF 和 error。
Tip:不要在 event-based server 中阻塞
event-based server 能够提供 fine-grained scheduling control,但前提是不能调用任何会阻塞 caller 的接口。否则 event loop 会停止,client 会一直等待,所有 connection 都无法推进。
为什么 single-CPU event loop 不需要 locks
在 single CPU、single-threaded event loop 中,一次只有一个 event handler 在执行,另一个 thread 不会在 handler 中途插入。因此基本 event-based approach 中通常不需要 acquire/release lock,threaded program 中常见的 concurrency bug 也不会以同样方式出现。这个结论严格依赖 single-loop 假设;一旦并行执行多个 handler,保护 shared state 的问题会重新出现。
Blocking system call 的具体例子
假设 client 请求 server 从 disk 读取文件并返回。handler 需要调用 open(),再调用一系列 read();metadata 或 data 不在 memory 时,这些调用可能向 storage system 发起 I/O。thread-based server 中,发起 I/O 的 worker 可以睡眠,其他 threads 继续服务;event-based server 只有主 event loop,因此一个 blocking handler 会让整个 server 停住,CPU 和其他 connections 都被浪费。故“没有 blocking calls”是 event model 的基本约束,而不是可选优化。
Asynchronous I/O 与完成通知
以 Mac 的 AIO API 为例,程序先准备 AIO control block:
struct aiocb {
int aio_fildes; // file descriptor
off_t aio_offset; // file offset
volatile void *aio_buf; // buffer location
size_t aio_nbytes; // transfer length
};
int aio_read(struct aiocb *aiocbp);
int aio_error(const struct aiocb *aiocbp);
aio_read() 成功后立即返回;aio_error() 返回 0 表示完成,返回 EINPROGRESS 表示仍在进行。若同时有几十或几百个 outstanding I/O,逐个 polling 并不理想;一些系统使用 UNIX signal 在 I/O 完成时通知 application。没有 asynchronous disk I/O 的系统,可以采用 hybrid:用 events 处理 network packet,用 thread pool 管理 outstanding disk I/O。
Figure 33.2:UNIX signal handler 示例
signal 可以将一个正在运行的 process 暂停,转而执行 signal handler,handler 返回后再恢复原来的 execution。下面的程序捕获 SIGHUP:
void handle(int arg) {
printf("stop wakin’ me up...\n");
}
int main(int argc, char *argv[]) {
signal(SIGHUP, handle);
while (1)
; // doin’ nothin’ except catchin’ some sigs
return 0;
}
运行后可以用 kill 发送 signal:
prompt> ./main &
[3] 36705
prompt> kill -HUP 36705
stop wakin’ me up...
prompt> kill -HUP 36705
stop wakin’ me up...
HUP、INT、SEGV 等 signal 各有语义;kernel 也可能发送 SIGSEGV 报告非法 memory access,未配置 handler 时通常会终止 process。signal infrastructure 很庞大,不能在本章一页中完整介绍;使用时还必须遵守 signal-safety 约束。
Manual stack management 与 continuation
thread-based server 可以自然地写成:
int rc = read(fd, buffer, size);
rc = write(sd, buffer, size);
read() 返回后,thread stack 上的 sd 仍然告诉程序应该写到哪个 socket。event-based server 发起 asynchronous read 后,handler 已经返回;完成 event 到来时,程序必须自行保存下一步所需 state。Adya 等人把这称为 manual stack management。
continuation 的做法是将 sd 等信息放进以 fd 为 key 的 hash table;disk I/O 完成后,handler 根据 fd 查出 continuation,再执行最后的 socket write。callback、future/promise 与显式 state machine 都是在不同抽象层次表达同一思想。
Event model 仍然困难的四个方面
- 多核:要利用多个 CPU,必须并行运行多个 event handler;critical section 和 locks 随即重新出现,现代 multicore system 上不再能保持“无 lock 的简单 event handling”。
- 隐式 blocking:handler 发生 page fault 时也会阻塞;即使代码没有显式 blocking call,paging 仍可能让整个 server 停止。
- API 语义变化:routine 从 non-blocking 变为 blocking 后,调用它的 handler 必须被拆成两段;因此必须持续监控 event 所使用 API 的 blocking semantics。
- I/O API 不统一:network I/O 可以用
select()管理,但 disk I/O 往往需要 AIO;很难用单一、统一的接口管理全部 outstanding I/O。
本章 Summary(按官方原文)
event-based server 把 scheduling control 交给 application,但代价是更高的复杂度,以及与 paging 等现代系统机制的集成困难。目前没有单一模型成为普适最优解;threads 与 events 很可能会作为同一个 concurrency 问题的两种方案长期共存。继续阅读相关 research paper,或亲自编写 event-based code,才能进一步理解这些取舍。
源文档核对记录
- 官方源文档:
threads-events.pdf,Version 1.10,共 12 页。 - 已核对源章节:33.1–33.9。
- 已核对图件:Figure 33.1–33.2;
select()event loop 与 UNIX signal handler 均按原文位置保留为 code block。 - 原文没有需要单独下载的 raster image;本章的主要图件是代码 listing,概念流程已用 Mermaid 或代码表达。
完整 References
- [A+02] Atul Adya、Jon Howell、Marvin Theimer、William J. Bolosky、John R. Douceur,Cooperative Task Management Without Manual Stack Management,USENIX ATC ’02,2002。
- [FHK84] Daniel P. Friedman、Christopher T. Haynes、Eugene E. Kohlbecker,Programming With Continuations,1984。
- [N13] Node.js Documentation。
- [O96] John Ousterhout,Why Threads Are A Bad Idea (for most purposes),USENIX ’96。
- [PDZ99] Vivek S. Pai、Peter Druschel、Willy Zwaenepoel,Flash: An Efficient and Portable Web Server,USENIX ’99。
- [SR05] W. Richard Stevens、Stephen A. Rago,Advanced Programming in the UNIX Environment,Addison-Wesley,2005。
- [vB+03] Rob von Behren、Jeremy Condit、Feng Zhou、George C. Necula、Eric Brewer,Capriccio: Scalable Threads for Internet Services,SOSP ’03。
- [WCB01] Matt Welsh、David Culler、Eric Brewer,SEDA: An Architecture for Well-Conditioned, Scalable Internet Services,SOSP ’01。
评论 (0)