Maps to: CMU 15-213/15-513/14-513 Fall 2026, Lecture 21 (Nov 17), slide deck
concprog. Reading: CS:APP3e §12.1–§12.3. Sources: the public Fall 2026 slides and CS:APP. The code is original to these notes and run on an Apple M4 Pro (12 cores: 8 performance + 4 efficiency), macOS. All servers are real and bind the loopback interface only. Code:code/lecture21/. Reading time: ~90 minutes; ~20 more for the demos.
0. How to read this lecture
0.1 Learning goals
After this lecture you should be able to:
- Say precisely why an iterative server fails, and demonstrate it with a measurement.
- Build a concurrent server in all three styles — process-based, event-based (
select), thread-based (Pthreads) — and state the trade-offs of each. - List what a thread shares with its peers and what is private, and explain why that makes threads both cheap and dangerous.
- Apply the three Pthreads idioms: detach (or join), give each thread its own argument, and let the thread own its descriptor.
- Recognize unintended sharing (the
&ibug) and fix it. - Name the four classic concurrency hazards — race, deadlock, livelock, starvation — as the agenda for Lectures 22–24.
0.2 Prerequisites and scope
- Lecture 20: the sockets interface and the iterative echo server this lecture replaces.
- Lecture 16:
fork, descriptor sharing, reaping. Lecture 17: theSIGCHLDhandler the process-based server needs. - Lecture 18: RIO. Every server here reads sockets with it.
- In scope: CS:APP §12.1–§12.3 — the three concurrency mechanisms, threads vs processes, the shared-memory model, unintended sharing.
- Out of scope here: synchronization itself (Lectures 22–23) and parallel speedup (Lecture 24). This lecture creates concurrency; the next three make it correct and fast.
- Policy: the proxy lab wants a concurrent proxy. These notes contain no proxy code — only echo servers, which is the textbook’s own teaching vehicle.
0.3 Section → code map
| Section | Idea | Demo in code/lecture21/ |
|---|---|---|
| §1 | the iterative server’s flaw, measured | multiclient.c + Lecture 20’s server |
| §2 | process-based concurrency | 01_process_server.c |
| §3 | event-based concurrency | 02_select_server.c |
| §4 | thread-based concurrency | 03_thread_server.c |
| §5 | unintended sharing | 04_unintended_sharing.c |
1. The problem: one slow client ruins everything
Lecture 20’s echo server accepts a connection, serves it to completion, then accepts the next. With one client at a time that is invisible. The flaw appears the moment a slow client and fast ones arrive together — and “slow” needs no malice, just a bad network.
multiclient.c constructs exactly that: client 0 connects and then holds the connection for 600 ms without sending; clients 1–3 connect 150 ms later and send immediately. Each client reports when it finished. Against Lecture 20’s unmodified iterative server:
ITERATIVE client 0: 604 ms clients 1-3: 604, 604, 604 ms <- BLOCKED
Every fast client paid the slow client’s entire delay. The server was not overloaded — it was idle, waiting for one socket while three others had data ready. Being fast earned nothing.
Reading these numbers. The fast clients start 150 ms after the slow one (so the slow one is certainly accepted first), so their best possible finish is ≈150 ms plus a few ms of service. Compare 155–189 ms against 604 ms in what follows.
The fix is concurrency: more than one logical flow of control, so that progress on one client does not depend on progress on another. There are exactly three ways to get it, and they are the rest of the lecture.
1.1 The vocabulary of what can go wrong
Concurrency is hard because the bugs are schedule-dependent: the program is correct for most interleavings and wrong for a few, so it passes your tests and fails in production. Four hazards have names, and the next three lectures are organized around them:
- Race — the result depends on the order of two unsynchronized operations (Lecture 22).
- Deadlock — flows wait for each other in a cycle, so none proceeds (Lecture 23).
- Livelock — flows keep executing but make no progress.
- Starvation — one flow never gets its turn while others are served (Lecture 23).
2. Process-based: fork per client
The simplest concurrency uses only Lecture 16’s machinery: after accept, fork. The child serves that one client and exits; the parent loops straight back to accept.
PROCESS (fork) client 0: 604 ms clients 1-3: 189, 184, 188 ms
The fast clients now pay only their own service time. 01_process_server.c is short, but two details are easy to get wrong and both come from Lectures 16–17.
2.1 Descriptors are shared, so both sides must close
fork copies the descriptor table, so immediately after it both processes hold both descriptors (Lecture 18’s open-file table, refcount 2):
if (pid == 0) { /* child */
close(listenfd); /* no use for the request queue */
echo_loop(connfd);
close(connfd);
_exit(0);
}
close(connfd); /* PARENT: CRITICAL -- the child owns it now */
The parent’s close(connfd) is the bug that is hardest to find. If the parent keeps its copy, the open-file entry’s refcount never reaches zero, so the connection is never fully closed: the client waits forever for an EOF that cannot arrive, while the server looks perfectly healthy and its descriptor table slowly fills. Nothing in the output would tell you.
2.2 Children must be reaped — asynchronously
The parent spends its life blocked in accept, so it cannot sit in wait. Reaping must happen in a SIGCHLD handler, with Lecture 17’s WNOHANG loop because several children can die between deliveries:
while (waitpid(-1, NULL, WNOHANG) > 0) reaped++;
A related wrinkle: SIGCHLD arriving while the parent is in accept makes that call fail with EINTR. The handler sets SA_RESTART, and the accept loop still retries on EINTR — belt and braces, because accept is not guaranteed restartable everywhere.
2.3 Trade-offs
Good: trivially correct, because processes share no memory — there are no races to reason about. A crash in one client’s handler cannot corrupt another’s. Bad: a whole process per client (address space, page tables, descriptor table) is the most expensive option, and sharing anything between clients (a cache, a counter) requires real IPC — pipes or shared memory. For a server whose clients are independent, it is a perfectly good choice.
3. Event-based: one process and select
The reason the iterative server blocks is that it waits on one descriptor. select() removes that restriction: give the kernel a set of descriptors and it reports which are ready. Touch only those and nothing ever blocks — so one process can interleave many conversations.
EVENT (select) client 0: 603 ms clients 1-3: 156, 156, 156 ms
02_select_server.c keeps a pool: an array of connected descriptors plus the master set. Each pass:
pool.ready_set = pool.read_set; /* select() OVERWRITES its argument */
select(maxfd + 1, &pool.ready_set, NULL, NULL, NULL);
if (FD_ISSET(listenfd, &pool.ready_set)) { /* a connection is pending */ }
/* then service every connfd that is ready */
Three things to note:
- The listening descriptor is just another member of the set. When it is ready, a connection is pending; when a connected descriptor is ready, data is pending. One uniform loop handles both.
selectmodifies the set you pass it, turning it into the ready set. The master set must be copied every iteration — a classic beginner bug that produces a server which handles one client and then goes deaf.- Each client needs its own
rio_t. This is the deep point. A buffered reader may already hold part of the next line, so that buffer belongs to the connection. In a thread or a process the conversation’s state lives implicitly on its call stack; with one shared flow of control there is no such stack, so you must materialize the state by hand.
3.1 Trade-offs
Good: no process or thread creation cost; complete control over scheduling (you can prioritize clients); and — underrated — no concurrency bugs, because there is only one flow of control and therefore nothing to synchronize. This is why high-performance servers (nginx, redis) and every GUI toolkit are event-based.
Bad: the logic is turned inside out. Every place you would naturally wait must become a stored state, so a protocol with several steps becomes an explicit state machine. Worse, there is no pre-emption: one long computation (or one blocking call made by mistake) stalls every client. And a single event loop cannot use more than one core. Production designs therefore often combine the two: several processes or threads, each running an event loop.
selecthas a hard limit (FD_SETSIZEdescriptors) and costs O(n) per call because it rescans the whole set. Real servers useepoll(Linux) orkqueue(BSD/macOS), which register interest once and report only what changed. The model is identical; only the scaling differs.
4. Thread-based: a pthread per client
A thread is a flow of control inside a process. Threads of one process share the address space; each has its own stack and registers. “One thread per client” buys the straight-line logic of the process-based server at a fraction of the cost.
THREAD (pthread) client 0: 604 ms clients 1-3: 155, 155, 155 ms
4.1 What is shared and what is private
This table is the thread model, and almost every threading bug is a misunderstanding of it:
| Private to each thread | Shared by all threads in the process |
|---|---|
| stack (so: local variables) | global variables |
| registers, program counter | the heap (everything malloc’d) |
| thread ID | the descriptor table |
errno (per-thread by definition) | code, and the current directory |
So two threads can trample each other’s data without passing a pointer anywhere — merely by both touching a global. That is the price of the cheapness.
4.2 The three idioms
03_thread_server.c shows all three, each a classic trap:
static void *serve_client(void *vargp)
{
int connfd = *((int *)vargp);
free(vargp); /* (2) we own the argument */
pthread_detach(pthread_self()); /* (1) nobody will join us */
/* ... echo loop on our own stack-local rio_t ... */
close(connfd); /* (3) we own the descriptor */
}
- Detach or join. A thread that is neither leaks its resources on exit — the thread version of Lecture 16’s zombie. A per-client thread is nobody’s business to join, so it detaches itself.
- Give each thread its own argument. The acceptor
mallocs oneint, fills it in beforepthread_create, and the thread frees it. §5 shows what the shortcut costs. - The thread closes the descriptor, not
main. Descriptors are shared, so acloseinmainwould break the thread that is still using it. Ownership must be unambiguous.
4.3 Trade-offs
Good: much cheaper than processes (no address space to duplicate; context switches between threads of one process are cheaper), and sharing data between clients is free — a shared cache is just a global. Can use multiple cores. This is the usual default.
Bad: that same free sharing. The demo’s served counter needs a mutex, because served++ from two threads loses updates — Lecture 22’s subject. One thread corrupting memory or crashing takes down the whole process. And thread-per-client still costs a stack (often ~512 KB–8 MB of virtual address space) per client, so very large servers use a bounded thread pool fed by a work queue (Lecture 23’s producer/consumer).
4.4 Which should you use?
| Process | Event loop | Thread | |
|---|---|---|---|
| Sharing | none (needs IPC) | trivial (one flow) | free, and dangerous |
| Cost per client | highest | lowest | low |
| Uses many cores | yes | no (one loop) | yes |
| Concurrency bugs | none by construction | none by construction | races, deadlock |
| Code shape | natural | inside out | natural |
| Isolation/robustness | best | worst (one crash kills all) | worst |
At this lecture’s scale the three concurrent designs are indistinguishable (189/156/155 ms): the fork cost is visible but small, and four clients stress nothing. The honest summary is that the correctness gap (blocked vs not blocked: 604 ms vs ~155 ms) is enormous while the performance gap between the three needs far more clients to matter. Choose on the sharing and robustness rows, not on these numbers.
5. Unintended sharing: the &i bug
pthread_create takes one void *, so the obvious thing is to pass a pointer to the loop variable:
for (int i = 0; i < N; i++)
pthread_create(&tid, NULL, worker, &i); /* WRONG */
Every thread receives the same address. main keeps incrementing that variable while the new threads start up, so a thread reading *p a moment later sees whatever i has reached. 04_unintended_sharing.c counts the damage with 16 threads:
broken ids received: 16 16 16 16 16 16 16 16 16 16 16 16 16 16 16 16
16 thread(s) received 1 DISTINCT value(s); 16 of the 16 expected ids never arrived
16 thread(s) read a value outside 0..15 (main's loop had already finished, so i == 16)
=> CORRUPT: threads did not get the ids they were 'given'
Not a scramble — total collapse. Every thread read i’s post-loop value, 16. Not one received the id it was “given”. The fix gives each thread private memory:
int *argp = malloc(sizeof(int));
*argp = k; /* filled BEFORE the thread exists */
pthread_create(&tid[k], NULL, worker_fixed, argp); /* the thread frees it */
fixed ids received: 0 1 3 4 5 7 8 9 10 6 11 12 13 14 2 15
=> a correct permutation of 0..N-1
(The order still varies — threads finish whenever they finish — but every value arrives exactly once, every run.)
This is unintended sharing: i was never meant to be shared, but threads share the address space by default, so passing its address shared it. The rule that follows: sharing is the thing you must argue for, not against. Pass a copy unless you deliberately want sharing — and if you do, you need a lock.
Why the demo is reliable and the bug is not. The worker pauses 1 ms before reading, which makes the race certain instead of merely likely. Without the pause the bug might hide on a fast machine and appear on the grader’s. The counts differ run to run: a race is not a bug you can test away; it is a bug you must reason away.
Summary
- An iterative server serializes clients: measured, three fast clients all finished at 604 ms because one client held the server for 600 ms. Concurrency is the fix.
- Process-based (
forkper client): correct by construction (no shared memory), most expensive, needs the parent toclose(connfd)and aSIGCHLDreaper with aWNOHANGloop. - Event-based (
select): one process, no concurrency bugs, total scheduling control — but the logic is inside out (state must be materialized: onerio_tper client), there is no pre-emption, and it cannot use several cores.selectoverwrites its set, so copy the master each pass. - Thread-based: cheap, natural code, shares memory for free and for danger. Private = stack/registers/
errno; shared = globals, heap, descriptors. Idioms: detach, own your argument, own your descriptor. - All three concurrent designs measured the same here (155–189 ms); pick on sharing, robustness and core use, not on micro-benchmarks.
- Unintended sharing: passing
&ito 16 threads delivered the single value 16 to all of them. Give each thread its own copy. - The four hazards — race, deadlock, livelock, starvation — are the agenda for Lectures 22–24.
Common pitfalls
- Parent forgets
close(connfd)after forking: the connection never closes and the client hangs with no symptom on the server. - No
SIGCHLDreaper in the process server: zombies accumulate. - Ignoring
EINTRfromaccept: a signal makes the server exit on a spurious “error”. - Not copying the
fd_setbeforeselect: it works once, then never again. - One shared
rio_tin an event loop: buffered data from one client is handed to another. - Passing
&i(or any pointer to changing storage) to a thread. - Forgetting to detach or join: leaked thread resources.
- Closing the connected descriptor in
mainwhile a thread still uses it. - Assuming a global is safe because you never passed a pointer to it — threads share it anyway.
- Testing a race away. Passing tests prove nothing about schedules you did not hit.
Exercises
-
Why 604 ms? Explain exactly why all four clients finished at 604 ms against the iterative server, even though three of them sent their data instantly.
Answer
The server was inside the slow client's `rio_readlineb`, which blocked for the full 600 ms. It had not yet returned to `accept`, so the other three connections sat in the listening socket's **queue**, established but unserved. Only after the slow client was finished did the server accept and serve them — within a millisecond or two each, hence all finishing together at ≈604 ms. -
The missing
close. A process-based server forgetsclose(connfd)in the parent. Describe the symptom from the client’s side and from the server’s.Answer
The child finishes and closes its copy, but the parent's copy keeps the open-file entry's refcount above zero, so the connection is never fully closed: **the client blocks forever waiting for EOF**. On the server, nothing appears wrong except that descriptors are never released, so the process slowly exhausts its descriptor table and `accept` eventually fails. -
One
rio_t. In theselectserver, what goes wrong if all clients share a single buffered reader?Answer
The reader's buffer may hold bytes read from client A (part of a later line). When client B is serviced, `rio_readlineb` returns **A's buffered data** as if it were B's. Clients receive each other's text and the protocol desynchronizes. Buffered state belongs to the connection, so each needs its own `rio_t`. -
Shared or private? For a thread, classify: a local
char buf[100]; a global counter; amalloc’d buffer whose pointer is in a global;errno; descriptor 4.Answer
**Private**: the local `buf` (it is on the thread's own stack) and `errno` (per-thread by definition). **Shared**: the global counter; the `malloc`'d buffer (the heap is shared and the pointer is reachable); and descriptor 4 (the descriptor table is per *process*). -
The
&ifix, two ways. Give two correct alternatives topthread_create(&tid, NULL, w, &i).Answer
(a) `malloc` an argument per thread, fill it before `pthread_create`, and have the thread `free` it (what the demo does). (b) Pass the *value* through the pointer itself — `pthread_create(..., (void *)(intptr_t)i)` and cast back inside — which works for small integers. A third: give each thread its own slot in an array (`&args[i]`), since no thread then shares storage with another. -
Which design? You must serve 50,000 mostly-idle long-lived connections that share a large read-only cache. Which style, and why?
Answer
**Event-based** (with `epoll`/`kqueue`), probably one loop per core. 50,000 processes or threads would cost enormous memory in stacks/page tables while nearly all are idle, and the work per event is tiny, so the event loop's weakness (no pre-emption) does not bite. The shared read-only cache needs no locking in any design, but is free here. -
Mixed design. Why do real servers often run several processes, each with an event loop, instead of choosing one style?
Answer
To get both properties: the event loop handles very many concurrent connections cheaply within one flow (no synchronization), while having several processes uses **multiple cores** and provides **isolation** — one crashing process does not take the service down. It also sidesteps the event loop's inability to use more than one core.
The related lab
Lab 7 (proxylab) requires a concurrent proxy, so this lecture supplies the mechanism and Lecture 23 the synchronization for its cache. Per the course’s academic-integrity policy these notes contain no lab solutions and no proxy code — the demos are echo servers, the textbook’s own teaching vehicle, with no caching, no HTTP parsing and no proxy logic.
Further reading
- CS:APP3e §12.1–§12.3 (process-, event- and thread-based concurrency) and practice problems 12.1–12.5. §12.3’s
echoservert.cis the reference for demo 03. man 2 select,man 2 kqueue,man 3 pthread_create,man 3 pthread_detach.- Dan Kegel’s “C10K problem” essay for the historical argument between these three styles, and the nginx architecture notes for a modern mixed design.
Preview of Lecture 22: Synchronization — basic
Threads shared memory for free, and the bill arrives now. Lecture 22 starts with the simplest possible broken program — two threads incrementing one counter — and shows the updates being lost. It then builds the tools to fix it: progress graphs to see which interleavings are unsafe, critical sections and mutual exclusion, mutexes, and semaphores with their P/V operations — plus what each one actually costs, measured.
术语表 (Glossary, English → 中文)
| English | 中文 |
|---|---|
| concurrency | 并发 |
| concurrent server | 并发服务器 |
| iterative server | 迭代式服务器 |
| logical control flow | 逻辑控制流 |
| process-based concurrency | 基于进程的并发 |
| event-based concurrency | 基于事件的并发 |
| thread-based concurrency | 基于线程的并发 |
| thread | 线程 |
| Pthreads | POSIX 线程库 |
pthread_create / pthread_join | 创建 / 等待线程 |
pthread_detach | 分离线程 |
thread ID (pthread_self) | 线程 ID |
| peer threads | 对等线程 |
| thread context (stack, registers) | 线程上下文(栈、寄存器) |
| shared address space | 共享地址空间 |
| private / shared variable | 私有 / 共享变量 |
| unintended sharing | 意外共享 |
| thread pool | 线程池 |
select / fd_set / FD_ISSET | 多路复用及其宏 |
epoll / kqueue | 高效事件通知机制 |
| readiness / ready set | 就绪 / 就绪集合 |
| event loop | 事件循环 |
| state machine | 状态机 |
| pre-emption | 抢占 |
SIGCHLD reaping | 回收子进程 |
EINTR / SA_RESTART | 被中断 / 自动重启标志 |
| descriptor sharing | 描述符共享 |
| race (condition) | 竞态条件 |
| deadlock | 死锁 |
| livelock | 活锁 |
| starvation | 饥饿 |
| mutex | 互斥锁 |
| isolation / robustness | 隔离性 / 健壮性 |