Operating Systems · Lecture Notes
Chapter 4: Threads
A process holds together all the resources of a running program: its address space, open files, and signal handlers. Often, though, several activities inside a single process must make progress at the same time. A browser draws the page while it waits for data from the network; a web server answers hundreds of requests at once. The thread is the answer to this need. Flows of execution that share the same address space but each run with their own program counter, registers, and stack provide concurrency without paying the cost of creating a process. These notes begin with the definition of a thread and the reason it is needed. They then use Amdahl’s law to examine the limits of parallel programming on multicore processors. They compare user-level and kernel-level threads and the N:1, 1:1, and M:N mapping models. Thread creation with Pthreads and Java, thread pools, fork-join, and implicit approaches such as OpenMP and GCD are presented with code. The last section is devoted to the problems that threads bring with them: fork(), signals, cancellation, thread-local storage, reentrant code, and race conditions.
Learning outcomes
- Concept
- Distinguish a thread from a process; say which state is shared by all threads and which is private to each thread.
- Performance
- Distinguish concurrency from parallelism, and use Amdahl’s law to compute the speedup achievable with a given number of cores and its upper bound.
- Models
- Compare user-level and kernel-level threads and the N:1, 1:1, and M:N mapping models in terms of switching cost, blocking, and use of multiple cores.
- Programming
- Create threads with Pthreads and Java, pass arguments, obtain results, and wait for them; recognize implicit approaches such as thread pools, fork-join, OpenMP, and GCD.
- Problems
- Explain race conditions, non-reentrant code, thread-local storage, cancellation, signal delivery, and the behavior of
fork()in a multithreaded process. - Real systems
- Interpret the Linux
clone()call, Java 21 virtual threads, and the Go runtime in terms of the mapping models.
4.1Basic concepts
The process concept is the operating system’s basic tool for isolating programs from one another. Every process has its own address space; one process can neither see nor corrupt another’s memory. This isolation is valuable for security, but it becomes an obstacle for tasks that must work together on the same data. If two processes are to share the same data, a shared memory region must be set up or messages must be sent; both are laborious and slow. The thread leaves isolation at the process level and allows several flows of execution inside a single address space.
4.1.1What is a thread?
The execution of a program can be thought of from two separate angles. The first is resources: the program occupies a place in memory, opens files, makes network connections, starts child processes. The second is execution: the processor carries out the program’s instructions in order, a program counter points to the next instruction, registers hold intermediate values, and the stack keeps track of function calls. The classic process concept combines these two angles: every process has both its resources and a single flow of execution. The thread concept separates the two.
A process is a program in execution. The owner of resources such as the address space, open files, child processes, signal handlers, and identity information is the process.
A thread is a flow of execution within a process. It has its own program counter (PC), register set, stack, and state. The thread is the basic unit of processor use and scheduling.
Tanenbaum sums up this distinction in a single sentence: the process groups resources together, and the thread is the entity that is executed on the processor. A process contains one or more threads. All of them see the same address space; a value that one writes to a global variable can be read by another at once. On the other hand, each thread can be at a different place in the program, call different functions, and work with different local variables.
The operating system keeps a process control block (PCB) for every process. A similar structure is needed for threads: the thread control block (TCB). The TCB holds the thread’s identifier (tid), its state, the saved PC and register values, the stack pointer (SP), its priority, and a pointer to the thread-local storage area. The resource information is not in the TCB but in the PCB of the process to which the thread belongs. Figure 4.1 shows this relationship.
task_struct structure.An old name for threads is lightweight process (LWP). The word “lightweight” points to the cost. Creating a new process requires setting up or copying the address space, preparing page tables, and duplicating the file table. A new thread needs only a stack and a TCB; the address space already exists. For the same reason, switching between two threads is also cheaper than switching between two processes.
Thinking of a thread as a “small process” and assuming that each thread has its own memory. Threads have no separate address space. Global variables, data allocated on the heap, and the code are common to all threads. Only the execution state is separate: the PC, registers, stack, and thread-local variables.
4.1.2Why multiple threads?
Most of today’s applications are multithreaded. A web browser, an integrated development environment (IDE), a game engine, a database server, or a web server runs with dozens of threads. There are several reasons for this.
- Different tasks run in separate flows. An application may have to update the screen, fetch data from the network, answer network requests, and check spelling at the same time. Each task is written in its own thread as sequential code, as if it were the only job in the program.
- A waiting task does not stop the others. While waiting for disk or network, that thread blocks, but the other threads in the same process keep making progress.
- Threads are cheap. Creating a process is expensive; creating a thread is much cheaper.
- Threads simplify the program. Each flow remains sequential code that can be read from start to finish. Doing the same job with a single flow forces the programmer to save by hand where each task left off.
The operating system kernel is multithreaded as well. The kernel threads whose names appear in square brackets when you look with the ps command on Linux are an example: kthreadd creates the other kernel threads, kworker threads carry out deferred work, and ksoftirqd handles software interrupts. Figure 4.2 shows three threads inside an application process and the kernel that schedules them.
4.1.3Single-threaded and multithreaded processes
A single-threaded process has a single flow of execution: one PC, one register set, and one stack. The program can be in only one place at a time. In a multithreaded process the code, global data, and open files are still one each; but each flow has its own registers and its own stack. Figure 4.3 shows the two cases side by side.
The distinction in the figure is the source of almost every problem with threads. Everything in the shared row is common data that all threads can access at the same time. What one thread writes to a global variable, the other threads see at once. This makes cooperation easy; but if two threads try to change the same variable at the same time, the result can be corrupted. The items in the private row, on the other hand, let each flow continue its own work without losing it.
4.1.4Shared and private items
Knowing which item is kept per process and which per thread is the first step toward writing a multithreaded program correctly. Table 4.1 lists this distinction.
| Per process (shared by all threads) | Per thread (private) |
|---|---|
| Address space: code, global variables, heap | Program counter (PC) |
| Open files, sockets | Registers |
| Child processes | Stack and stack pointer |
| Pending alarms (timers) | State: running, ready, waiting, terminated |
| Signal handlers | Thread ID, signal mask |
| Identity and accounting information | Thread-local storage (TLS), errno |
The left column of the table shows that the operating system manages resources at the process level. If one thread opens a file, the file descriptor is valid for the whole process; another thread can read and write with the same descriptor and can even close the file. Signal handlers are also process-wide: a handler that one thread installs for SIGINT runs no matter which thread the signal is delivered to.
The items in the right column belong to the execution itself. Two threads can run the same function at the same time; since each one’s local variables are on its own stack, they do not get mixed up. Variables such as errno, which “look global but are private to the thread,” are provided by thread-local storage (4.6.5).
Thinking “the stack is private to the thread, so no other thread can touch it.” The stack is private but not protected. All stacks are in the same address space; a faulty pointer can read or corrupt data on another thread’s stack. The hardware does not prevent this, because the page table is the same for all threads.
A summary rule is enough for the rest of this chapter: access to shared data requires synchronization. Every global variable, every heap object, and every open file that several threads write is open to a race condition unless it is protected by a lock or an atomic operation (4.6.7).
4.1.5Each thread has its own stack
Function calls and local variables must be kept separately for each flow. While thread A is inside a function f, thread B may call g. If both used the same stack, B’s frame would overwrite A’s frame, and when A returned from f it would jump to the wrong address. That is why every thread has its own stack. Figure 4.4 shows how the stacks are placed in the address space of a process with three threads.
mmap region; at the bottom are the heap growing upward, the global data, and the code. Each thread’s SP points to its own stack.On Linux, the glibc library places the stack of a new thread in an anonymous memory region allocated with mmap. The default stack size is usually the value of ulimit -s; on most distributions this is 8 MiB. Not all of this 8 MiB is placed in physical memory at once: thanks to virtual memory, only the pages that are touched actually consume memory.
Stacks grow downward, and if there is nothing between two stacks, an overflowing stack can overwrite its neighbor. To prevent this, a guard page is placed at the end of each stack. The guard page is marked inaccessible; the moment an overflowing stack touches this page, a page fault occurs and the process is terminated with the SIGSEGV signal. The error is thus noticed at once instead of silently corrupting the neighboring stack.
The stack size can be adjusted. In Pthreads, the desired size is given with pthread_attr_setstacksize before the thread is created. In Java, the -Xss option determines the stack size of every platform thread. For a thread that recurses deeply the stack may need to be enlarged, and for thousands of short-lived threads it may need to be reduced.
The virtual threads introduced in Java 21 change this situation. The stack frames of a virtual thread are kept not in a fixed-size memory region but in objects on the heap, and grow as needed. That a virtual thread can start with a stack of a few hundred bytes makes it possible for millions of virtual threads to exist at the same time (4.3.8).
A server creates one platform thread for each connection; the default stack size is 8 MiB. For 10,000 connections, how many bytes of virtual address space are reserved for stacks alone?
- One stack is 8 MiB = 8 × 220 bytes.
- 10,000 stacks: 10,000 × 8 MiB = 80,000 MiB ≈ 78.1 GiB.
- A 64-bit address space can easily hold this, and pages that are not touched consume no physical memory. But at least a few pages of each stack are used; every thread also has a TCB and a kernel stack in the kernel. Tens of thousands of platform threads therefore spend noticeably more resources than virtual threads or an event-driven design.
4.1.6Example: a three-threaded word processor
To show why threads are useful, Tanenbaum’s classic example is a word processor. While editing a book of hundreds of pages, the user deletes a line on page one. Deleting this line requires all the following pages to be reformatted. At the same time, the user wants to keep typing, and the program must save the document to disk at regular intervals. Figure 4.5 assigns these three jobs to three threads.
- Interaction
- It handles key and mouse events immediately. No matter how much work there is in the background, the interface does not freeze.
- Formatting
- When a line is deleted, it rearranges hundreds of pages in the background. When the user jumps to page 600, that page is most likely ready.
- Autosave
- It writes the document to disk at regular intervals. It does not make the user wait while disk I/O is pending.
The same design could not be built with three separate processes. All three jobs must work on the same document; if the document were copied into three separate address spaces, every change would have to be passed on to the others. The shared address space is the key advantage here. A single-threaded design, on the other hand, would be left with two bad options: either keyboard input goes unanswered until formatting finishes, or the formatting code stops every few lines to poll the keyboard. The second option makes the code unreadable.
4.1.7A multithreaded web server
The most familiar use of threads is in servers. A web server receives a large number of requests every second. Some of the requests are for frequently accessed pages, and these pages are ready in a web page cache in memory. For the other requests the page must be read from disk, which takes milliseconds. If the server handles every request in sequence, a request waiting for the disk makes all the requests behind it wait.
In Tanenbaum’s design the server process has two kinds of threads. The dispatcher thread reads the requests coming from the network. For each request it picks an idle worker thread, hands the request over to it, and wakes it up. The worker first looks for the page in the cache; if it cannot find it, it reads it from disk and sends the response. Figure 4.6 shows this arrangement at a moment when one of the workers is blocked on disk.
read() call to read it from disk. Meanwhile the dispatcher and worker 3 keep running.Four moments stand out in this design. A request arrives and the dispatcher reads it from the network. The dispatcher picks an idle worker, hands the request over to it, and wakes it up. If worker 1 finds the page in the cache, it sends the response at once; it does not go to disk. A new request goes to worker 2, and if the page is not in the cache, worker 2 blocks on disk. The last case is the important one: worker 2 blocking stops only worker 2. The dispatcher keeps accepting new requests, and worker 3 keeps handling another request.
The code of the two threads is extremely simple. The dispatcher reads the next request in an infinite loop and hands it to a worker:
while (TRUE) {
get_next_request(&buf); /* from net */
handoff_work(&buf); /* to worker */
}get_next_request(&buf) blocks until a request arrives from the network and writes the request into the buffer buf. handoff_work(&buf) passes the request to an idle worker and wakes that worker. After that the dispatcher does not concern itself with what happens to the job; it goes straight back to the top of the loop. The worker’s code is a similar loop:
while (TRUE) {
wait_for_work(&buf);
look_for_page_in_cache(&buf, &page);
if (page_not_in_cache(&page))
read_page_from_disk(&buf, &page);
return_page(&page);
}The worker blocks in wait_for_work until the dispatcher gives it a job. When a job arrives, it looks for the page in the cache (look_for_page_in_cache). If the page is not in the cache, it reads it from disk with read_page_from_disk; this call blocks until the disk read finishes. Finally return_page sends the page to the client, and the worker goes back to the top of the loop to wait for a new job.
Both pieces of code are sequential and readable. The blocking read call stops only the worker that calls it. In a single-threaded server the situation is different: for a page that is not in the cache the whole process blocks, the processor sits idle while the disk is awaited, and requests that arrive in the meantime wait in a queue. In the multithreaded server the work is handed to a worker, and the server keeps accepting new requests.
4.1.8Code trace: the dispatcher and the workers
Let us follow how the design works with a concrete scenario. The server process has three threads: the dispatcher and two workers, W1 and W2. Initially the dispatcher is listening on the network, and both workers are blocked in wait_for_work. Only the page a.html is in the cache. One request arrives first for b.html and then for a.html. The code being traced is the two loops put together:
/* dispatcher thread */
while (TRUE) {
get_next_request(&buf);
handoff_work(&buf);
}
/* worker thread */
while (TRUE) {
wait_for_work(&buf);
look_for_page_in_cache(&buf, &page);
if (page_not_in_cache(&page))
read_page_from_disk(&buf, &page);
return_page(&page);
}| Step | Event | Dispatcher | W1 | W2 | Disk | Cache |
|---|---|---|---|---|---|---|
| 0 | start | running | blocked (waits for work) | blocked (waits for work) | idle | a.html |
| 1 | request 1 arrives: b.html | running | blocked (waits for work) | blocked (waits for work) | idle | a.html |
| 2 | handoff_work: request 1 → W1 | running | ready | blocked (waits for work) | idle | a.html |
| 3 | W1 looks in the cache: miss | blocked (network) | running | blocked (waits for work) | idle | a.html |
| 4 | W1 read_page_from_disk | blocked (network) | blocked (disk) | blocked (waits for work) | reading | a.html |
| 5 | request 2 arrives: a.html | running | blocked (disk) | blocked (waits for work) | reading | a.html |
| 6 | W1 is busy: request 2 → W2 | running | blocked (disk) | ready | reading | a.html |
| 7 | W2 finds a.html in the cache | blocked (network) | blocked (disk) | running | reading | a.html |
| 8 | W2 return_page: request 2 answered | blocked (network) | blocked (disk) | running | reading | a.html |
| 9 | disk finishes, W1 wakes up, request 1 answered | blocked (network) | running | blocked (waits for work) | idle | a.html, b.html |
| 10 | both workers wait for work again | blocked (network) | blocked (waits for work) | blocked (waits for work) | idle | a.html, b.html |
The key step in the trace is step 4. W1 blocks to read from disk, but only W1 stops; the other threads in the same process keep running. While the disk is awaited, the dispatcher takes the second request and, because W1 is busy, gives it to W2. W2 finds the page in the cache and answers. As a result request 2 is answered before request 1. When the disk read finishes, W1 wakes up, also puts the page into the cache, and sends it to the first client. Figure 4.7 shows steps 4 and 8 side by side.
a.html from the cache.In a single-threaded server, request 2 would have waited until the disk read finished, even though its page was ready in memory. The multithreaded server uses this wasted time by overlapping waiting with computation. Each piece of code also stays sequential and readable.
Counting the answering of request 2 before request 1 as an error. In a multithreaded server, requests are completed not in the order they arrive but in the order they become ready. Because each request answers on its own connection, the change of order does not break correctness; on the contrary, it shortens the average response time.
4.1.9Three ways to design a server
There are three basic options for how a server copes with blocking operations. Tanenbaum and Bos compare them as in Table 4.3.
| Model | Parallelism / overlap | System calls | Programming |
|---|---|---|---|
| Multithreaded process | yes | blocking | sequential code, easy |
| Single-threaded process | no | blocking | easy but slow |
| Finite-state machine (event-driven) | yes (I/O overlaps) | nonblocking + notification / interrupt | hard: the state of each request is saved by hand |
The third model needs some explanation. In an event-driven server there is a single thread, but this thread never blocks. When it needs to read from disk, it makes a nonblocking call and moves on to other work, knowing that it will receive a notification when the read finishes. Meanwhile it records in a table where the half-finished request stands, which page it is waiting for, and whom to answer. When the notification arrives, it finds that request in the table and continues where it left off. The program thus turns into a finite-state machine: each request is a small machine that moves from one state to another. I/O overlaps with computation, but the sequential code structure that the thread model provides is lost.
Today the event-driven model is widespread: nginx, Node.js, and Redis use it. On Linux, epoll and io_uring, and on BSD and macOS kqueue, are interfaces for watching many connections with a single thread. Most real servers combine the two approaches: one event loop runs per core, and work that might block (e.g., disk access, compression) is sent to a thread pool.
On a single-processor server, 3/4 of the requests are served from the cache and use 10 ms of processor time. The remaining 1/4 have a 50 ms disk wait in addition to 10 ms of processor time. The disk can serve many requests at once. How many requests per second does the server answer if it is single-threaded, and if it is multithreaded?
- Single thread. While the disk is awaited, the process blocks and the processor sits idle. The average duration of a request is 3/4 × 10 + 1/4 × (10 + 50) = 7.5 + 15 = 22.5 ms. 1000 / 22.5 ≈ 44.4 requests are answered per second.
- Multiple threads. While the worker waiting for the disk is blocked, another worker uses the processor; the disk wait overlaps with computation. The bottleneck is the processor alone, and each request needs 10 ms of processor time. 1000 / 10 = 100 requests are answered per second.
- Comment. Because there is a single processor, the gain does not come from parallelism; it comes from the overlap of blocking calls with computation. The same overlap can be achieved with a single event-driven thread, but the code becomes more complicated.
4.1.10Benefits of multithreading
The examples so far bring out the four basic benefits of multithreaded programming.
- Responsiveness
- The program keeps responding even if part of it blocks or performs a long computation. In user interfaces this property is decisive: if a long operation started by pressing a button runs in a separate thread, the window does not freeze.
- Resource sharing
- Threads share the process’s memory and files by default. For the same sharing between processes, a shared memory region or a message-passing mechanism must be set up; with threads nothing extra is done.
- Economy
- Creating threads and switching between them is cheap compared with processes: the address space is not copied and the page tables do not change.
- Scalability
- A single multithreaded process can run on several cores at the same time. A single-threaded process uses only one core, however many cores the machine has.
The figures often quoted in textbooks, that “creating a thread is 30 times and switching between threads 5 times faster than for processes,” rest on an old Solaris measurement. These ratios do not hold on every system. On Linux, processes and threads are created with the same clone() call (4.6.9), so the difference between their creation costs is smaller. The real gain is that the memory mapping is not copied and the address translation cache is preserved during switching.
4.1.11The cost of a context switch
The processor’s move from one flow of execution to another is called a context switch. The difference between the two kinds of switch explains why threads are cheaper. Figure 4.9 compares the two kinds.
In both switches the kernel saves the running flow’s registers, PC, and SP and loads those of the new flow. In a switch between processes one more step is added: the base address of the page table is changed. On x86 processors this address is kept in the CR3 register. When the new address space is entered, the old entries in the translation lookaside buffer (TLB), which stores the records that translate virtual addresses into physical addresses, are no longer valid. If the processor cannot tag the entries with an address space identifier (PCID or ASID), the TLB is flushed. After that, the new process runs slowly until its first memory accesses refill the TLB and the data caches.
The cost has two components. The direct cost is the time to save and load the registers and to run the scheduler; on today’s processors it is on the order of microseconds. The indirect cost comes from memory accesses that slow down after the switch because of cold caches and TLB misses. The indirect cost is often larger than the direct cost. In a switch between threads of the same process, most of the indirect cost disappears because the address space does not change.
For user-level threads (4.3.2), switching is cheaper still. The switch is done not by the kernel but by a library function in user space. There is no trap and no entry into the kernel; the switch comes down to an ordinary function call of a few instructions.
Thinking that the cost of a context switch is only the time to save registers. Saving the registers may take a few hundred nanoseconds, but the cache and TLB misses that follow can slow the program down for much longer. A program that runs more threads than necessary spends the processor on refilling caches instead of useful work because of frequent switches.
4.2Multicore programming
Until about 2005, processors came to market at higher clock speeds every year, and single-threaded programs sped up on their own. When power consumption and heat stopped this increase, manufacturers turned to putting several cores on the same chip. Today a laptop has 8–16 cores and a server 64–128. The way to benefit from these cores is to split the program into parts that can run at the same time. Threads are the most direct tool for this.
4.2.1Concurrency and parallelism
Two words that are used interchangeably in everyday language carry different meanings in operating systems.
Concurrency is the progress of several tasks in the same time interval. The tasks need not run at the same instant; they can also progress interleaved on a single core.
Parallelism is the execution of several tasks at the same instant. It requires at least two cores or processing units.
Consider four tasks on a single-core machine. The scheduler gives each a short time slice: first T1, then T2, T3, T4, and T1 again. Because the slices are short, to the human eye the four tasks appear to progress together. In reality only one runs at any instant. This is concurrency but not parallelism. If the same four tasks run on a two-core machine, T1 and T3 share the first core and T2 and T4 the second. Now at every moment two tasks truly run at the same time: this is parallel execution. Figure 4.10 compares the two cases.
Parallelism requires concurrency: two tasks running at the same time also progress in the same time interval. The converse is not true: a concurrent program can run on a single core without parallelism. The same program behaves differently on two different pieces of hardware. On a single core, threads only interleave; on multiple cores they truly run at the same time and can truly access shared data at the same time.
Thinking that using threads on a single core is pointless. Even without parallelism, concurrency is valuable: while one thread is blocked, another runs (the server in Example 4.2 sped up by more than a factor of two on a single processor). Likewise, it is wrong to think there are no race conditions on a single core: the time slice can end in the middle of a read-increment-write sequence.
4.2.2The challenges of multicore programming
A larger number of cores does not speed up programs by itself. The programmer or the compiler must divide the work among the cores. Silberschatz groups the difficulties of this task under five headings; memory effects must be added to them.
- Identifying tasks
- Finding activities in the application that are independent of one another and can run in parallel. Some algorithms divide naturally (the sum of an array); others proceed step by step and cannot be divided.
- Balance
- Tasks should be of similar size. If one of four cores gets four times as much work as the others, that core determines the total time. Giving a separate core to a very small task does not pay either; the cost of starting the task exceeds the gain.
- Data splitting
- The data that the tasks access must also be divided among the cores. If all the cores access the same data, parallelism turns into contention.
- Data dependency
- If one task is waiting for the result of another, access must be synchronized. Dependencies reduce the part that can run in parallel.
- Testing and debugging
- The order of execution may change in every run. A bug may appear once in a hundred runs and may never show up under a debugger.
- Memory effects
- If different variables are on the same cache line and two cores write to them, the cache coherence mechanism keeps moving the line between the cores. Although logically nothing is shared, the cores slow each other down. This situation is called false sharing.
There are tools that help find races: ThreadSanitizer, enabled with the -fsanitize=thread option in GCC and Clang, Valgrind’s Helgrind tool, and Java Flight Recorder. But no tool catches all races; tools examine only the accesses that occur in that run. Reducing sharing at the design stage is the most effective method.
4.2.3Data and task parallelism
There are two basic ways of dividing work among cores. In data parallelism, the data is divided into pieces and each core performs the same operation on its own piece. In task parallelism, the work is divided into different tasks and each core performs a different operation; the tasks may use the same data or different data. Figure 4.11 shows the two ways on the same eight-element array.
Summing an array of N elements with four cores is the typical example of data parallelism: each core sums N/4 elements, and in the end the four partial sums are combined. Graphics processors are the extreme case of this model; thousands of simple cores apply the same instruction to different pixels or matrix elements. A program that computes the statistics of an array is an example of task parallelism: one core finds the minimum, one the maximum, one the mean, and one the standard deviation. Real applications usually use both together.
4.2.4Amdahl’s law
How much can we speed up a program by increasing the number of cores? Almost every program has a part that cannot be parallelized: reading the input, combining the results, work done in sequence behind a lock. This part takes the same time no matter how many cores are added. Gene Amdahl’s observation, made in 1967, is that this serial part sets a firm upper limit on the speedup.
Let the program’s running time on a single core be 1 unit. A portion S of this time is serial, and 1 − S can be parallelized. On N cores the serial part still takes S; the parallel part is divided equally among N cores and takes (1 − S) / N. The speedup is the ratio of the old time to the new time.
A program with serial fraction S speeds up on N cores by at most a factor of
speedup ≤ 1 / ( S + (1 − S) / N )
As N → ∞ the parallel term goes to zero, and the upper bound of the speedup becomes 1 / S.
The inequality sign says that the formula is an optimistic bound. The formula assumes that the parallel part divides perfectly and that there is no communication or synchronization cost among threads. The real speedup falls below this bound. Another measure is efficiency: the ratio of the speedup to the number of cores, that is, how well each core is used.
25% of a program’s running time is serial (S = 0.25). What are the time and the speedup on 1, 2, and 4 cores? What is the upper bound of the speedup?
- N = 1: time 0.25 + 0.75 / 1 = 1, that is, 100%. Speedup 1×.
- N = 2: time 0.25 + 0.75 / 2 = 0.25 + 0.375 = 0.625, that is, 62.5%. Speedup 1 / 0.625 = 1.60×. The number of cores doubled, but the speedup is not 2×.
- N = 4: time 0.25 + 0.75 / 4 = 0.25 + 0.1875 = 0.4375, that is, 43.75%. Speedup 1 / 0.4375 ≈ 2.29×. Efficiency 2.29 / 4 ≈ 57%.
- N → ∞: the parallel part approaches zero and the serial 25% remains. The speedup is at most 1 / 0.25 = 4×.
Figure 4.12 gives the essence of the law visually. As cores are added, only the blue part gets shorter. After some point almost the whole bar consists of the orange part, and new cores hardly change the time. Even a serial part that looks small limits scaling noticeably.
On an eight-core machine, a computation is to be sped up by at least a factor of 6. What is the largest the serial part can be?
- Let us turn the speedup formula into an equation: 6 = 1 / (S + (1 − S) / 8). From this, S + (1 − S) / 8 = 1/6.
- Multiply both sides by 8: 8S + 1 − S = 8/6, that is, 7S = 8/6 − 1 = 1/3.
- S = 1/21 ≈ 0.0476. The serial part can be at most about 4.8%; at least 95.2% of the code must be parallel.
- Check: 1 / (1/21 + (20/21) / 8) = 1 / (1/21 + 5/42) = 1 / (7/42) = 6.
Confusing the serial fraction with the parallel fraction. The S in the formula is the serial (non-parallelizable) fraction. If the question says “80% of the program can be parallelized,” then S = 0.2, not 0.8. Another common mistake is to confuse speedup with time: 0.625 is the time, and 1.60 is the speedup.
4.2.5Amdahl curves and Gustafson’s law
The consequences of Amdahl’s law are even more striking when plotted for different serial fractions. Figure 4.13 shows the speedup on a logarithmic scale of core count for four programs whose parallel fractions are 50%, 75%, 90%, and 95%.
| Serial fraction S | N = 2 | N = 4 | N = 8 | N = 16 | N = 64 | N = 1024 | Limit 1/S |
|---|---|---|---|---|---|---|---|
| 0,50 | 1,33 | 1,60 | 1,78 | 1,88 | 1,97 | 2,00 | 2 |
| 0,25 | 1,60 | 2,29 | 2,91 | 3,37 | 3,82 | 3,99 | 4 |
| 0,10 | 1,82 | 3,08 | 4,71 | 6,40 | 8,77 | 9,91 | 10 |
| 0,05 | 1,90 | 3,48 | 5,93 | 9,14 | 15,42 | 19,64 | 20 |
Two conclusions follow from the table. First, the limit is very sensitive to the serial fraction: reducing the serial part from 10% to 5% raises the limit from 10 to 20. Second, the return from adding cores diminishes quickly. Even if 95% of the program is parallel, the speedup on 1024 cores is only 19.6×; more than 98% of the cores are working in vain. In reality, because of synchronization and communication overhead, the speedup stays below even these values.
Amdahl’s law assumes that the problem size stays fixed: the same job is done with more cores. In 1988 John Gustafson asked a different question: as the number of cores grows, the problem usually grows too. Someone doing weather forecasting who gets 1024 cores does not settle for making the same forecast faster; they make a more detailed forecast with a finer grid. In this case the parallel part grows with the cores, while the serial part stays roughly constant. With this assumption, Gustafson’s law says that the scaled speedup is
scaled speedup = S + (1 − S) · N
Here S is the serial share of the running time of the enlarged problem on N cores. For example, for S = 0.1 and N = 16 the scaled speedup is 0.1 + 0.9 · 16 = 14.5; Amdahl’s law gives 6.4 with the same values. The two laws do not contradict each other; they answer different questions. Amdahl answers “how fast can I finish this job?”; Gustafson answers “how large a job can I do in the same time?”
4.2.6Code trace: Amdahl speedup
The short C program below prints the speedup on 1, 2, 4, 8, and 16 cores for a program whose serial fraction is 10%, and at the end prints the upper bound:
double S = 0.1; /* serial fraction */
int N = 1; /* cores */
while (N <= 16) {
double sp = 1 / (S + (1 - S) / N);
printf("N=%2d %.2fx\n", N, sp);
N = N * 2;
}
printf("limit %.0fx\n", 1 / S);The program starts with S = 0.1 and N = 1. The while loop runs as long as N does not exceed 16. In each round the speedup sp is computed with Amdahl’s formula, printed with two decimal places by printf, and N is doubled. When N = 32 the condition is false, the loop ends, and the last line prints the limit 1 / S. Table 4.5 traces each round of the loop.
| Round | N | S + (1 − S) / N | sp | Output line | Increase over the previous round |
|---|---|---|---|---|---|
| 1 | 1 | 0,1 + 0,9 = 1 | 1,00 | N= 1 1.00x | — |
| 2 | 2 | 0,1 + 0,45 = 0,55 | 1,82 | N= 2 1.82x | ×1,82 |
| 3 | 4 | 0,1 + 0,225 = 0,325 | 3,08 | N= 4 3.08x | ×1,69 |
| 4 | 8 | 0,1 + 0,1125 = 0,2125 | 4,71 | N= 8 4.71x | ×1,53 (%53) |
| 5 | 16 | 0,1 + 0,05625 = 0,15625 | 6,40 | N=16 6.40x | ×1,36 (%36) |
| — | 32 | 32 ≤ 16 is false: the loop ends; the last line is limit 10x | |||
The last column shows the diminishing returns with numbers. The number of cores doubles in each round, but the ratio of increase in speedup falls from 1.82 to 1.36. Going from 8 to 16 cores raises the speedup by only 36%. That the decimal separator in the output is a point comes from C’s printf formatting.
As N goes to infinity, the parallel part falls to zero, the serial 10% remains, and the speedup can never exceed 10×. Even on 16 cores the speedup is 6.4×; the efficiency is 6.4 / 16 = 40%. 60% of the cores are effectively spent waiting for the serial part.
4.3Thread models
The question of who manages threads has two extreme answers. Either all management is done in a library in user space and the kernel knows nothing about threads, or the kernel recognizes every thread and schedules it itself. These two extremes and the hybrid solutions between them determine the cost of threads, their blocking behavior, and whether they can use multiple cores.
4.3.1User-level and kernel-level threads
User-level threads are managed in a library that runs in user space, that is, in a run-time system. The kernel believes that each process has a single flow.
Kernel-level threads are threads that the kernel recognizes and schedules itself. Linux, Windows, and macOS use this approach.
Figure 4.15 shows where the thread table lives in the two approaches. At the user level, each process has its own run-time system and its own thread table; the kernel knows only the process table. At the kernel level, the thread table is in the kernel and contains the threads of all processes.
4.3.2User-level threads
Managing threads entirely in user space may look odd at first, but this approach has serious advantages.
- No kernel support is needed. Even on a kernel with no thread support, threads can be implemented as a library. Many UNIX versions were like this until the 1990s.
- Each process keeps its own table. For each thread the table stores the PC, the registers, the SP, and the state. It is similar to the kernel’s process table, but it lives in user memory.
- Switching is very fast. Switching from one thread to another needs no trap, no entry into the kernel, no change of memory mapping, and no TLB flush. A switch is a function call of a few instructions.
- The scheduling algorithm can be chosen. Each process can use a scheduling algorithm that suits it; for example, to run a garbage-collector thread at the most suitable moment.
The disadvantages are more fundamental, and they explain why user-level threads have been abandoned at the operating-system level.
- A blocking system call stops the whole process. If a thread calls
readand blocks on disk, the kernel blocks the whole process, because for the kernel the process has a single flow. The other threads cannot run even if they are ready. The solutions are not elegant: using wrappers (jackets) that first test the call withselectand switch to another thread if there is no data to read, or replacing all calls with their nonblocking versions. - A page fault also blocks the whole process. If a page a thread accesses is not in memory, the kernel holds the process while it brings the page from disk; the library does not even know about it.
- The clock interrupt does not reach the library. The kernel can interrupt the process when its time slice expires, but which thread runs within the process is decided by the library. Because the library has no clock interrupt, if a thread does not give up the CPU voluntarily (
yield), the other threads never run. - A single process cannot use several cores. Because the kernel sees the process as a single flow, it places it on a single core at a time.
4.3.3Code trace: thread_yield at the user level
To see how simple a user-level switch is, let us follow the thread_yield function of a library step by step. The code below is a simplified version of a real library. PC and SP are pseudo-variables standing for the processor’s program counter and stack pointer; a real library reads and writes them with a few lines of assembly.
enum { READY, RUNNING, WAITING };
struct tcb { int pc, sp, state; } T[3];
int cur = 0; /* running */
void thread_yield(void) { /* in library */
T[cur].pc = PC; T[cur].sp = SP;
T[cur].state = READY;
do cur = (cur + 1) % 3;
while (T[cur].state != READY);
T[cur].state = RUNNING;
PC = T[cur].pc; SP = T[cur].sp;
}struct tcb holds each thread’s saved PC, SP, and state; T[3] is a table for three threads. cur is the index of the thread running at that moment. thread_yield first saves the running thread’s PC and SP values into the table and makes it READY. The do … while loop then advances cur circularly and keeps going until it finds a READY thread. The thread found is made RUNNING, and its saved PC and SP values are loaded into the processor. The function’s return instruction now returns on the new thread’s stack; execution continues where the new thread left off.
Initially T0 is running; in the processor PC = 0x124 and SP = 0x8FF0. The T0 row of the table holds old values (0x100, 0x9000); these are left over from the last time T0 was saved. T1 is waiting for a lock in the library (WAITING), and T2 is ready and last gave up the processor at PC = 0x480, SP = 0xB000. T0 calls thread_yield() voluntarily.
| Step | Line executing | T0 (pc, sp, state) | T1 | T2 | cur | CPU |
|---|---|---|---|---|---|---|
| 0 | (start) | 0x100, 0x9000, X | 0x300, 0xA000, W | 0x480, 0xB000, R | 0 | PC=0x124 SP=0x8FF0 |
| 1 | T[cur].pc = PC; T[cur].sp = SP; | 0x124, 0x8FF0, X | same | same | 0 | same |
| 2 | T[cur].state = READY; | 0x124, 0x8FF0, R | same | same | 0 | same |
| 3 | cur = (cur + 1) % 3; | same | same | same | 1 | same |
| 4 | while (T[1].state != READY): W, the loop continues | same | same | same | 1 | same |
| 5 | cur = (cur + 1) % 3; | same | same | same | 2 | same |
| 6 | while (T[2].state != READY): R, the loop ends | same | same | same | 2 | same |
| 7 | T[cur].state = RUNNING; PC = …; SP = …; | 0x124, 0x8FF0, R | 0x300, 0xA000, W | 0x480, 0xB000, X | 2 | PC=0x480 SP=0xB000 |
| 8 | T2 runs for a while and calls thread_yield() at PC = 0x48C: save, READY, cur = (2 + 1) % 3 = 0, T0 is READY | 0x124, 0x8FF0, R | same | 0x48C, 0xAFF8, R | 0 | PC=0x48C SP=0xAFF8 |
| 9 | T0 is made RUNNING, its registers are loaded | 0x124, 0x8FF0, X | same | 0x48C, 0xAFF8, R | 0 | PC=0x124 SP=0x8FF0 |
In steps 1 and 2 T0’s state is saved. This is an ordinary function call: there is no trap and no entry into the kernel. In steps 3–6 the table is scanned; T1 is skipped because it is waiting, and T2 is chosen because it is ready. In step 7 T2’s registers are loaded. The whole switch ends in a few instructions. In step 8 T2 also gives up the processor voluntarily, and the turn comes around to T0 again. In step 9 T0 continues from address 0x124, that is, where it left off. Figure 4.16 shows the start and step 7.
cur points to T0, and the processor has PC = 0x124. (b) Step 7: T0’s values have been saved and it is READY, T1 is still WAITING, T2 is RUNNING, and the processor has been loaded with PC = 0x480, SP = 0xB000. The kernel sees a single flow throughout.Assuming that user-level threads are also interrupted by the time slice. If T2 entered an infinite computation loop and never called thread_yield(), T0 would wait forever. The clock interrupt goes to the kernel; the kernel can interrupt the process and run another process, but when the process runs again, T2 continues where it left off. The library has no chance to step in.
4.3.4The blocking call: N:1 and 1:1
The most serious problem of user-level threads is blocking system calls. To make the problem visible, let us put two models side by side. In the many-to-one (N:1) model, all the user threads of a process run on a single kernel thread. In the one-to-one (1:1) model, every user thread has its own kernel thread.
read(); the kernel sees only K1 and blocks it, so U2 and U3 wait too.In the N:1 model, when U1’s read() call reaches the kernel, the kernel sees a single schedulable entity belonging to this process: K1. It blocks K1 until the read finishes. Even if U2 and U3 are ready, there is no kernel thread to run them; the whole process stops. In the 1:1 model the same call blocks only U1’s kernel thread, K1. U2 and U3 have their own kernel threads (K2 and K3); the scheduler keeps running them in parallel on two cores.
4.3.5Kernel-level threads
With kernel-level threads, the kernel keeps a thread table that contains the same information as the user-level table (registers, state, and the like). The consequences of this arrangement can be listed as follows.
- Creating and terminating a thread is a system call. It is therefore more expensive than at the user level.
- If a thread blocks, the kernel picks another. The chosen thread need not be from the same process.
- A page fault holds only the thread that caused it.
- The threads of a process truly run in parallel on different cores.
- Every thread takes up space in kernel memory: the TCB and the kernel stack. Their number is therefore not unlimited.
Today Linux (NPTL, the Native POSIX Thread Library), Windows, and macOS use the 1:1 model. Because the cost of creating a kernel thread has fallen over the years, tens of thousands of kernel threads are not a problem. On Linux the number of threads is determined by three limits: the system-wide /proc/sys/kernel/threads-max, ulimit -u per user, and pids.max per control group. To observe the threads of a process, use ps -eLf (one line per thread), top -H, or the directory /proc/<pid>/task/; this directory contains a subdirectory for each thread.
4.3.6Mapping models
How user threads are mapped to kernel threads falls under four models. Figure 4.20 shows all four side by side.
- Many-to-one (N:1)
- Switching is fast, but a blocking call stops the whole process and there is no parallelism. Examples: Solaris green threads and GNU Portable Threads; both are historical today.
- One-to-one (1:1)
- There is true parallelism and each thread can block independently. The price is that every thread uses kernel resources. Linux, Windows, and macOS use this model.
- Many-to-many (M:N)
- Many user threads are multiplexed onto a smaller number of kernel threads. Creating a user thread is cheap, several cores are used, and when a thread blocks the run-time system can run the others on other kernel threads. The problem is the difficulty of implementation: two separate schedulers, one in user space and one in the kernel, make decisions without knowing about each other.
- Two-level (hybrid)
- In addition to M:N, a user thread can be permanently bound to a single kernel thread. A latency-sensitive thread thus gets a kernel thread of its own.
4.3.7Comparing the models
| Criterion | N:1 | 1:1 | M:N |
|---|---|---|---|
| Switching cost | very low | medium (kernel) | low |
| Blocking call | the whole process stops | only that thread | only that thread* |
| Multiple cores | cannot be used | can be used | can be used |
| Number of threads | very many | limited by kernel memory | very many |
| Implementation | easy (library) | easy | hard (two schedulers) |
The starred cell depends on a condition: in the M:N model, a thread blocking affects the others only if the run-time system does not notice the blocking call and move the other user threads to another kernel thread.
At the operating-system level, the M:N model has been abandoned. Solaris 9 and FreeBSD 7 moved to the 1:1 model because of the coordination problems between the two schedulers and the complexity of the implementation. The M:N model, however, has returned in language run-times. Go’s lightweight threads (goroutines), Erlang processes, and Java 21 virtual threads implement the M:N model not in the kernel but in the language’s run-time. Because the run-time itself manages the calls that could block, the biggest problem of the old M:N implementations disappears.
During its run, a program performs 500,000 thread switches. A user-level (N:1) switch takes 50 ns and a kernel-level (1:1) switch takes 2 µs. How much total time goes to switching in the two models? What happens when one of the threads performs a 10 ms disk read?
- N:1: 500,000 × 50 ns = 25,000,000 ns = 0.025 s.
- 1:1: 500,000 × 2 µs = 1,000,000 µs = 1 s. The user-level switch is 40 times cheaper, because there is no trap and no entry into the kernel.
- Disk read, N:1: The kernel sees a single kernel thread and blocks it. The whole process waits 10 ms; this time equals 200,000 user-level switches.
- Disk read, 1:1: Only the reading thread waits. The other threads keep running during those 10 ms, even in parallel on other cores.
- Conclusion. Switching cost alone does not decide the choice of model. In a program that does I/O, a single blocking call can wipe out most of the time that N:1 gains in switches. The M:N model tries to combine the two advantages: cheap switching and a run-time that does not block.
4.3.8Current M:N: virtual threads and Go
The virtual threads that became permanent with Java 21 (Project Loom) are today’s most widespread example of the M:N model. The JVM multiplexes many virtual threads onto a small number of platform threads. The platform thread that runs a virtual thread is called a carrier; carriers are ordinary kernel threads, and the operating system schedules them with the 1:1 model. Figure 4.21 shows these two layers.
When a virtual thread makes a blocking I/O call, the JVM unmounts it from its carrier: it saves the stack frames to the heap and parks the thread. The carrier becomes free and runs another virtual thread. When the I/O finishes, the parked thread is mounted on a carrier again and continues where it left off. V3, V6, and V8 in the figure are not blocked but parked; their carriers run other virtual threads in the meantime. The kernel sees only the carriers. That is why creating millions of virtual threads is possible. A virtual thread is started with Thread.ofVirtual().start(r).
The Go run-time describes the same idea with three letters. G is a Go thread (started with go f()). M is an operating-system thread (machine). P is a logical processor that represents the right to run Go code; its number is set by GOMAXPROCS and by default equals the number of cores. Each P has a queue of Gs waiting to be run. A P whose queue becomes empty steals work from another P’s queue. If a G enters a blocking system call, the run-time detaches the P from that M and gives it to another M; the other Gs keep running.
4.3.9Pop-up threads
In distributed systems, the traditional way of handling incoming messages is for a thread blocked in a receive call to wake up when a message arrives. The state of this thread, that is, its registers and stack, must be restored on every message. A faster option is to create a new thread to handle the message when it arrives. This thread is called a pop-up thread.
A pop-up thread is new; it has no history, registers, or stack contents to restore. The delay between the arrival of the message and the start of its processing is therefore low. The same idea is used inside the kernel too: some kernels handle interrupts in short-lived threads created when the interrupt arrives. A pop-up thread can be created with Pthreads as follows:
/* on message arrival */
pthread_t t;
pthread_create(&t, NULL, handle, msg);
pthread_detach(t); /* no join */pthread_create passes the message to the function handle as an argument. pthread_detach makes the thread detached: when the thread finishes, its resources are returned automatically and nobody needs to wait for it with pthread_join. Because it would be pointless for the server to wait one by one for the threads it creates for each incoming message, a detached thread is the natural choice here.
4.4Thread libraries
The programmer creates and manages threads through a thread library. The library offers an application programming interface (API) for creating, waiting for, terminating, and synchronizing threads. The library can be entirely in user space; in that case calling a library function is an ordinary function call. Or the library relies on kernel support, and most of its functions result in a system call.
4.4.1Libraries and two styles of use
- POSIX Pthreads
- The C API of Linux, macOS, and BSD systems. Besides creating and waiting for threads, it also provides the mutual exclusion lock (mutex) and the condition variable.
- Windows API
- Creates with
CreateThreadand waits withWaitForSingleObject. It is kernel-level and uses the 1:1 model. - Java
- Works with the classes
Thread,Runnable, andExecutorService. The Java virtual machine (JVM) uses the operating system’s threads, and since Java 21 also virtual threads. - C and C++ standards
- C11 brought the
<threads.h>header; C++11 broughtstd::threadand C++20std::jthread. These replaced the Boost.Thread library, which was formerly widespread. - Python
- Provides the
threadingmodule. However, the global interpreter lock (GIL) in the standard interpreter allows only one thread at a time to run Python code; parallelism is therefore not achieved for processor-heavy work. The GIL-free build, which arrived experimentally in Python 3.13, became a supported option in 3.14. - Go
- The statement
go f()starts a new Go thread. The run-time uses the M:N model; threads communicate through channels.
Threads are used in two different styles. In asynchronous use, the parent thread starts the child and continues with its own work; little data is shared between the two. The multithreaded web server is an example: the dispatcher gives the work to a worker and does not wait for its result. In synchronous use, the parent waits for its children to finish (join) and combines their results. This pattern is called fork-join: the work forks, the pieces run in parallel, and then they join again.
4.4.2POSIX Pthreads
Pthreads is the thread creation and synchronization API defined by the IEEE 1003.1c (POSIX.1c) standard. An important detail is that Pthreads is a specification, not an implementation. The standard says how the library should behave; it leaves it to the implementer whether this is done at user level or kernel level. On Linux, NPTL inside glibc implements Pthreads with the 1:1 model; on macOS and the BSDs too, Pthreads runs on kernel threads. A program that uses Pthreads is compiled with the command gcc prog.c -pthread.
| Call | Description |
|---|---|
pthread_create | Creates a new thread and runs the given function in it. |
pthread_exit | Terminates the calling thread. |
pthread_join | Waits for a given thread to finish. |
pthread_detach | Makes the thread detached: when it finishes, its resources are returned automatically; it is not joined. |
pthread_self | Returns the calling thread’s own identifier. |
sched_yield | Gives up the processor. (pthread_yield is nonstandard and was deprecated in glibc 2.34.) |
pthread_attr_init / _destroy | Initializes or destroys the attribute structure that holds settings such as stack size and detached state. |
The signature of pthread_create shows the general style of Pthreads: int pthread_create(pthread_t *tid, const pthread_attr_t *attr, void *(*func)(void *), void *arg). The identifier of the new thread is written to the first parameter. The second parameter gives the attributes; NULL means default settings. The third parameter is the function the thread will run; this function takes a single void * and returns a void *. The fourth parameter is the argument to be passed to that function. The call returns 0 on success and an error code on failure.
4.4.3Pthreads: create and wait
The first example is adapted from the program in Figure 4.11 of Silberschatz. The program adds up the integers up to an upper bound, which would come from the command line, in a separate thread; here the upper bound is given directly as the string "5". The lines #include <pthread.h>, <stdio.h>, and <stdlib.h> are not shown.
int sum; /* shared */
void *runner(void *param) {
int upper = atoi(param);
sum = 0;
for (int i = 1; i <= upper; i++)
sum += i;
pthread_exit(0);
}
int main(void) {
pthread_t tid;
pthread_create(&tid, NULL, runner, "5");
pthread_join(tid, NULL);
printf("sum = %d\n", sum);
return 0;
}sum is a global variable; both threads therefore see it. runner is the function that the thread will run. It converts its parameter to an integer with atoi, puts it into the variable upper on its own stack, adds the numbers from 1 to upper to sum, and terminates with pthread_exit(0). main starts the new thread with pthread_create, waits for it to finish with pthread_join, and prints the result.
| Step | main | runner | sum | Description |
|---|---|---|---|---|
| 1 | running | not yet | 0 | The process starts with a single thread; the global sum is zero-initialized. |
| 2 | pthread_create | ready | 0 | A new thread is created; runner("5") is a candidate to run. |
| 3 | pthread_join → waiting | running | 0 | The scheduler decides when runner starts. |
| 4 | waiting | upper = atoi("5") = 5 | 0 | upper is on runner’s own stack. |
| 5 | waiting | loop: 1 + 2 + 3 + 4 + 5 | 15 | The shared sum is updated. |
| 6 | waking up | pthread_exit(0) → done | 15 | runner ends; join returns. |
| 7 | printf | done | 15 | Output: sum = 15. |
The output of the program is the same on every run, because main reads sum only after pthread_join returns. Join guarantees that runner has finished all its writes. Without join, main could read sum before runner has even started and print 0. Worse, returning from main terminates the whole process; runner would die before it could finish its work. The observation in step 3 is important too: when pthread_create returns, there is no guarantee whatsoever that the new thread has started running. The scheduler decides which runs first.
main is waiting in pthread_join, and runner is running.4.4.4Multiple threads
To show data parallelism with Pthreads, let us divide the sum of the numbers from 1 to 1000 among four threads. Each thread adds 250 numbers.
#define N 4
long partial[N]; /* one cell each */
void *add_range(void *arg) {
long k = (long)arg; /* 0 .. N-1 */
for (long i = k*250 + 1; i <= (k+1)*250; i++)
partial[k] += i;
return NULL;
}
int main(void) {
pthread_t t[N];
for (long k = 0; k < N; k++)
pthread_create(&t[k], NULL, add_range, (void *)k);
long total = 0;
for (int k = 0; k < N; k++) {
pthread_join(t[k], NULL);
total += partial[k];
}
printf("%ld\n", total); /* 500500 */
}The thread number k is passed not as a pointer but as a value: the expression (void *)k places the number directly into the pointer field, and (long)arg in add_range takes it back out. Because long and a pointer have the same width, this conversion is safe. Thread number k adds the numbers from 250k + 1 to 250(k + 1) into its own cell partial[k]. main creates the four threads, then joins each in turn and adds its partial sum to the main total.
| k | Range | partial[k] |
|---|---|---|
| 0 | 1 … 250 | 31.375 |
| 1 | 251 … 500 | 93.875 |
| 2 | 501 … 750 | 156.375 |
| 3 | 751 … 1000 | 218.875 |
| Sum | 500.500 | |
The program has no race condition, because each thread writes only to its own cell and main reads a cell only after the owner of that cell has finished. Whatever order the threads run in, the result is always 500,500.
Passing the address of the loop variable, &k, as the argument. All four threads receive a pointer to the same variable k. Because the loop keeps incrementing k in the meantime, by the time a thread reads *arg, k may already be 2 or 4; two threads add the same range and one range is never added. When the loop ends, the lifetime of k ends too. The solution is to pass the value directly or to give each thread a separate memory cell.
There is also a performance trap in the code. The four cells of the partial array are next to each other in memory and fall on the same cache line. Because four cores write to this line continuously, the line goes back and forth between the cores: false sharing. If each thread accumulates the sum in a local variable first and writes it to partial[k] once at the end, the problem disappears.
4.4.5Passing arguments and getting results
A thread function has a single void * parameter and a single void * return value. To pass or receive several values, the values are put in a structure and the address of the structure is passed. The program below passes the lower and upper bounds of a range in a structure and gets back the total and the count in a structure as well.
typedef struct { int lo, hi; } range_t;
typedef struct { long total; int count; } result_t;
void *add_range(void *arg) {
range_t *a = arg; /* void* → type */
result_t *s = malloc(sizeof *s); /* on heap */
s->total = 0; s->count = 0;
for (int i = a->lo; i <= a->hi; i++) {
s->total += i; s->count++;
}
return s; /* = pthread_exit(s) */
}
int main(void) {
range_t a = { 1, 100 };
pthread_t t; void *ret;
pthread_create(&t, NULL, add_range, &a);
pthread_join(t, &ret); /* ret = s */
result_t *s = ret;
printf("%d numbers, total %ld\n", s->count, s->total);
free(s);
return 0;
}main creates the structure a on its own stack and passes its address as the argument. add_range converts the void * to its real type, range_t *. For the result, it allocates a result_t on the heap with malloc, zeroes its fields, and counts the numbers while adding those from 1 to 100 in the loop. The line return s; has the same effect as pthread_exit(s): the pointer is delivered to whoever waits for this thread with join. The pthread_join(t, &ret) in main writes this pointer into ret through the second parameter of type void **.
| Step | main stack | T stack | Heap |
|---|---|---|---|
| 1 | a = {1, 100} | no | — |
| 2 | a; pthread_create | arg → a | — |
| 3 | a | a = arg, s → heap | total = 0, count = 0 |
| 4 | a | i = 101 (loop ended) | total = 5050, count = 100 |
| 5 | a | frame removed | total = 5050, count = 100 |
| 6 | ret → heap, s = ret | T finished | total = 5050, count = 100 |
| 7 | printf, free(s) | T finished | (freed) |
The program prints 100 numbers, total 5050. Two lifetime questions stand out in the trace. The first is the lifetime of the argument: a is on main’s stack, and this frame lives until main joins T. It is therefore safe to pass its address. The second is the lifetime of the result: T’s stack disappears when T finishes, but the object on the heap goes on living. Ownership passes to main through join, and returning the memory (free) is now main’s job. Figure 4.24 shows two important moments.
a and s; in the structure on the heap total = 5050 and count = 100. (b) Step 6: T has finished and its stack is gone; main’s pointers ret and s point to the structure on the heap.4.4.6A common mistake: returning a result from the stack
Instead of allocating the result on the heap, keeping it on the thread’s own stack and returning its address is a frequent mistake in Pthreads programs:
void *add_range(void *arg) {
result_t s = { 0, 0 }; /* on T’s stack */
/* ... fill in s ... */
return &s; /* BUG */
}In the faulty version the result is the local variable s on T’s stack, and &s is returned. When the function returns, its frame is deleted. When the thread ends, its whole stack is released or may be given to another thread created later. When main reads the address it got from join, the result is undefined: a garbage value, SIGSEGV, or, worst of all, a value that sometimes looks correct. The last is the most dangerous, because the bug does not show in tests and appears in use. The correct version uses the heap:
void *add_range(void *arg) {
result_t *s = malloc(sizeof *s);
if (s == NULL) return NULL;
/* ... fill in s ... */
return s; /* on heap: lives on */
}The heap version is correct, but it brings two responsibilities. If malloc finds no memory, it returns NULL; the result is therefore checked before use, and the thread returns NULL. The owner of the result is now main: after using the pointer it got with pthread_join, it must free it, or the memory leaks.
void *ret;
pthread_join(t, &ret);
if (ret != NULL) {
printf("total = %ld\n", ((result_t *) ret)->total);
free(ret);
}ret in main still holds the old address (0x7f3a…e40); reading ret->total is undefined behavior.The same rule applies to the argument: the address given to a thread must stay alive for as long as the thread uses it. In most cases, GCC gives the warning -Wreturn-local-addr for functions that return the address of a local variable; this warning should be treated as an error.
4.4.7Java: Thread, start, and join
In Java every program starts with at least one thread, the main thread, which runs the main method. The shortest way to create a new thread is to give the Thread constructor the code to be run as a lambda expression. The program below does the sum of the Pthreads example in Java.
public class Sum {
static int total = 0;
public static void main(String[] a)
throws InterruptedException {
Thread t = new Thread(() -> {
for (int i = 1; i <= 5; i++) total += i;
});
t.start();
System.out.println("main: waiting");
t.join();
System.out.println("total = " + total);
}
}new Thread(lambda) only creates an object; no thread is running yet and the object’s state is NEW. t.start() starts a new operating-system thread, and the lambda runs in that thread. Meanwhile main keeps printing; the two threads can run at the same time. At t.join(), main waits in the WAITING state until t finishes. When t finishes the loop, total is 15 and t’s state becomes TERMINATED.
| Line | main | t |
|---|---|---|
new Thread(…) | RUNNABLE | NEW (created, not started) |
t.start() | RUNNABLE | RUNNABLE |
println("main: waiting") | RUNNABLE | RUNNABLE |
t.join() | WAITING (join) | RUNNABLE |
| (t finishes the loop) | waking up | TERMINATED |
println("total = " + total) | RUNNABLE | TERMINATED |
The program was compiled and run with the javac and java commands of JDK 21. Its two-line output is the same every time: first main: waiting, then total = 15. When two lines that print t.getState() were added to the program to observe the states, NEW was seen before start and TERMINATED after join.
The variable total is neither volatile nor protected by a lock; even so, it is guaranteed that main sees 15. The Java memory model says that all the writes a thread makes are visible to the thread that waits for it with join. This relationship is called the happens-before relationship. Besides waiting, join also provides visibility.
Calling run() instead of start(). t.run() is an ordinary method call: the lambda runs not in a new thread but inside the calling thread, that is, main. The program gives the right result but there is no concurrency at all. The difference is seen at once when Thread.currentThread().getName() is printed: inside run() the name is main. A Thread object can also be started only once; a second start() call throws IllegalThreadStateException (tried with JDK 21).
4.4.8Java 21: virtual threads
To show why virtual threads matter, let us write a program that creates 10,000 tasks. Each task sleeps for one second in its own virtual thread; the sleep stands in for waiting for a network response.
import java.time.Duration;
import java.util.concurrent.*;
import java.util.stream.IntStream;
public class Virtual {
public static void main(String[] args) {
try (var ex = Executors.newVirtualThreadPerTaskExecutor()) {
IntStream.range(0, 10_000).forEach(i ->
ex.submit(() -> {
Thread.sleep(Duration.ofSeconds(1));
return i;
}));
} // close(): waits for all tasks
System.out.println("done");
}
}Executors.newVirtualThreadPerTaskExecutor() returns an executor that creates a new virtual thread for each submitted task. IntStream.range(0, 10_000) generates the numbers from 0 to 9999, and for each of them ex.submit submits a task. The task sleeps for one second with Thread.sleep and returns its number. The try block is written in try-with-resources style: when the block ends, the executor’s close() method is called automatically, and this method waits until all the submitted tasks have finished. Finally done is printed.
If the program ran sequentially it would take 10,000 seconds, that is, about 2 hours 47 minutes. In measurements made with JDK 21 on two different machines, all the tasks finished in about 2 seconds and in 1.2 seconds. The second machine had 12 logical cores, and the tasks ran on 12 carrier threads. The measured time varies from machine to machine, but the order of magnitude does not: each of the ten thousand tasks releases its carrier while waiting, and a few carriers suffice for all the tasks.
Running the same program with 10,000 platform threads means 10,000 kernel threads and 10,000 stacks. This works on most systems, but it is expensive in memory and kernel resources; when the number of tasks reaches the hundreds of thousands, the system limits are hit. The area where virtual threads are suitable is tasks that spend much of their time waiting for I/O: servers that serve thousands of concurrent connections. There is no gain for processor-heavy work, because in that case the bottleneck is the number of cores. Virtual threads can also be created the classic way: Thread.ofVirtual().start(r) starts a virtual thread, while Thread.ofPlatform() returns a builder that creates platform threads.
4.5Implicit threading
4.5.1Specifying the task and leaving the threads to the run-time
When the number of threads reaches hundreds or thousands, creating, waiting for, and synchronizing each one by hand becomes both harder and error-prone. Implicit threading takes this burden off the programmer. The programmer specifies only the tasks, that is, the pieces of work that can run in parallel. The compiler and run-time libraries create the threads, distribute the tasks to them, and manage them. Table 4.13 lists the common approaches.
| Approach | Where | Idea |
|---|---|---|
| Thread pool | Java ExecutorService, the Windows thread pool | Ready threads take the tasks in the queue. |
| Fork-join | Java ForkJoinPool, parallel streams | Divide the task, solve the pieces in parallel, combine the results. |
| OpenMP | C, C++, Fortran | Parallel regions through compiler directives. |
| Grand Central Dispatch | macOS, iOS (libdispatch) | Blocks are put on dispatch queues. |
| oneTBB (formerly Intel TBB) | C++ template library | parallel_for, task scheduling, work stealing. |
4.5.2Thread pools
Suppose a multithreaded web server creates a new thread for every request. This design has two problems. The first is the cost of creating and then destroying a thread on every request; if the work is short, this cost can be larger than the work itself. The second is that there is no limit on the number of concurrent threads: a sudden burst of requests can create thousands of threads and exhaust memory and the processor.
A thread pool is a fixed (or bounded) number of threads that are created at the start and that take the tasks placed in a queue and run them in turn. A thread that finishes its task does not die; it takes the next task in the queue.
The pool creates a fixed number of threads at the start, and the application puts tasks in the queue. Idle workers take tasks from the queue; the cost of creating a new thread is not paid. When a worker finishes a task, it immediately takes the next. When the queue empties, the workers wait until the next task arrives. The number of concurrently running threads never exceeds the pool size. The benefits of a pool can be summed up in three points:
- Faster service. A ready thread takes the task at once; the creation cost has been paid once.
- It protects the system. The pool size puts an upper bound on the number of threads that can exist at the same time. A burst of requests increases not the number of threads but the length of the queue.
- It separates the task from the way it is run. The task says only what is to be done. Whether it runs delayed or periodically, and with what priority, is decided by the pool.
A rough rule is used for choosing the pool size. For processor-heavy tasks the size should equal the number of cores; in Java this number is found with Runtime.getRuntime().availableProcessors(). More than that gains no parallelism and only adds context switching and cache contention. For I/O-heavy tasks a larger pool is needed, because most threads are waiting. If a task’s wait time is W and its compute time is C, then about Nthreads ≈ Ncores × (1 + W / C) threads keep the cores busy.
A task running on a four-core machine computes for 10 ms and then waits 30 ms for the response of a remote service. How many threads should the pool have?
- The wait/compute ratio is W / C = 30 / 10 = 3.
- Nthreads ≈ 4 × (1 + 3) = 16.
- Interpretation: there are four threads per core. While one thread computes for 10 ms and then waits 30 ms, the other three use the same core in turn, and the core stays busy all the time. This number is a starting point; the real value is tuned by measurement. A pool that is too large consumes memory, and one that is too small leaves the processor idle.
4.5.3Java ExecutorService
Java’s java.util.concurrent package offers pools through the ExecutorService interface. The code fragment below gives four tasks to a pool of two threads; each task computes the square of its own number.
ExecutorService pool = Executors.newFixedThreadPool(2);
List<Future<Integer>> results = new ArrayList<>();
for (int g = 1; g <= 4; g++) {
final int n = g;
results.add(pool.submit(() -> n * n));
}
int total = 0;
for (Future<Integer> f : results)
total += f.get(); // waits for result
System.out.println("total = " + total);
pool.shutdown();Executors.newFixedThreadPool(2) creates a fixed pool of two threads. The loop submits one task for each of g = 1, 2, 3, 4. Inside the lambda the loop variable cannot be used directly, because Java requires that the local variables captured by lambdas not change afterward; that is why a new copy is taken in every round with final int n = g;. submit puts the task in the queue and immediately returns a Future object. A Future is a placeholder for a result that may not yet be ready. In the second loop, f.get() obtains the result of each task, waiting until it is ready if it is not. The shutdown() in the last line stops the pool from accepting new tasks; the running tasks finish and the threads terminate.
| Task | n | f.get() | sum |
|---|---|---|---|
| 1 | 1 | 1 | 1 |
| 2 | 2 | 4 | 5 |
| 3 | 3 | 9 | 14 |
| 4 | 4 | 16 | 30 |
When run with JDK 21, the program prints the following:
total = 30The result is deterministic: however the tasks are distributed to the two workers, the get() calls are made in the order of the list, and each returns the result of its own task. The Executors class has other factory methods too. newCachedThreadPool creates new threads as needed and closes idle ones after a while. newScheduledThreadPool is used for delayed and periodic tasks. newVirtualThreadPerTaskExecutor creates a new virtual thread for each task (4.4.8).
4.5.4Fork-join
Fork-join is the parallel counterpart of divide-and-conquer algorithms. If a task is larger than a threshold, it is split in two; the pieces are forked as separate tasks and can run on different threads of the pool. Small tasks that have reached the threshold are computed directly, sequentially. The parent task waits for its children (join) and combines their results. Figure 4.27 computes the sum of eight numbers with this method.
The three stages of the method can be read from the figure. First the large task is split, because it is larger than the threshold. In the fork step two subtasks are created; they can run on different threads of the pool. The subtasks are split again, and the leaves that reach the threshold (two elements) are computed directly: [3,1] = 4, [4,1] = 5, [5,9] = 14, [2,6] = 8. In the join step each parent waits for its children and combines them: 4 + 5 = 9, 14 + 8 = 22. At the root the result is 9 + 22 = 31. Fork-join is the typical example of synchronous thread use: every parent waits for the result of its children.
4.5.5ForkJoinPool and work stealing
For fork-join, Java offers the ForkJoinPool pool and the RecursiveTask<V> class in the java.util.concurrent package. A task that returns a result is derived from RecursiveTask and writes the compute() method. The class below sums the range [lo, hi) of an array; the fields a, lo, and hi and the constructor are not shown, for brevity.
class SumTask extends RecursiveTask<Long> {
protected Long compute() {
if (hi - lo <= LIMIT) { // small: do it
long s = 0;
for (int i = lo; i < hi; i++) s += a[i];
return s;
}
int mid = (lo + hi) / 2;
SumTask left = new SumTask(a, lo, mid);
SumTask right = new SumTask(a, mid, hi);
left.fork(); // start async
long rightSum = right.compute();
return left.join() + rightSum;
}
}
long s = ForkJoinPool.commonPool()
.invoke(new SumTask(a, 0, a.length));compute() first compares the length of the range with the threshold. If the range is small, it sums it with an ordinary loop and returns. If it is large, it splits it in the middle and creates two subtasks. left.fork() puts the left half in the queue of the worker that is running at that moment and returns at once; the task has not run yet. The right half is computed in the same thread, directly with right.compute(). In the last line, left.join() waits for the result of the left half and the two results are added. ForkJoinPool.commonPool() is the JVM’s shared pool; invoke starts the root task and waits for its result.
Running the right half directly in the same thread instead of forking it is a deliberate choice. If both halves were forked, the thread would wait for the two of them without doing anything. This way only one task enters the queue at each split, and the thread does not sit idle.
For an array filled with the numbers 1 to 100,000, the program prints total = 5000050000 on JDK 21. This value equals 100,000 × 100,001 / 2. The result is the same in a trial with a threshold of 1000 elements and a common pool of 11 threads.
How the pool balances the load matters too. In ForkJoinPool, each worker has its own double-ended queue (deque). A worker puts the tasks it forks at one end of its own queue and takes from that same end; this makes it continue with the most recently split, smallest task. A worker whose queue has become empty does not wait idle; it takes a task from the other end of another worker’s queue. This is called work stealing. At the other end there are usually the oldest, largest tasks; a single steal therefore carries a lot of work, and the chance of colliding with the owner is low.
4.5.6Code trace: a sum with fork-join
To see exactly what fork and join do, let us trace a small array in a pool with a single worker: a = {2, 7, 1, 8, 2, 8, 1, 8}, LIMIT = 2, and the call new ForkJoinPool(1).invoke(new Sum(a, 0, 8)). Choosing a single worker makes the trace deterministic: nobody steals tasks. The method being traced is this:
protected Long compute() { // LIMIT = 2
if (hi - lo <= LIMIT) {
long s = 0;
for (int i = lo; i < hi; i++)
s += a[i];
return s;
}
int mid = (lo + hi) / 2;
SumTask left = new SumTask(a, lo, mid);
SumTask right = new SumTask(a, mid, hi);
left.fork(); // to deque
long rightSum = right.compute();
return left.join() + rightSum;
}| Step | Event | Queue | Computed |
|---|---|---|---|
| 1 | Root [0,8): 8 − 0 = 8 > LIMIT, it splits | empty | — |
| 2 | left.fork(): [0,4) goes to the queue; does not run at once | [0,4) | — |
| 3 | right.compute(): [4,8) in the same thread | [0,4) | — |
| 4 | [4,8) splits: [4,6) goes to the queue | [0,4) [4,6) | — |
| 5 | [6,8): 2 elements, at the limit; summed directly | [0,4) [4,6) | [6,8) = 1 + 8 = 9 |
| 6 | left.join(): [4,6) is at the end of the queue and nobody has stolen it; the worker removes it and runs it itself | [0,4) | [4,6) = 2 + 8 = 10 |
| 7 | [4,8) combines and returns to the root | [0,4) | [4,8) = 10 + 9 = 19 |
| 8 | Root left.join(): [0,4) leaves the queue and runs; it splits, [0,2) goes to the queue | [0,2) | — |
| 9 | [2,4) leaf | [0,2) | [2,4) = 1 + 8 = 9 |
| 10 | join runs the leaf [0,2); [0,4) combines | empty | [0,2) = 2 + 7 = 9; [0,4) = 9 + 9 = 18 |
| 11 | The root combines | empty | [0,8) = 18 + 19 = 37 |
The program was run with JDK 21 and printed total = 37. When a trace line that prints the range and the result was added at the finish of each task, the tasks finished in exactly the order of the table: [6,8) = 9, [4,6) = 10, [4,8) = 19, [2,4) = 9, [0,2) = 9, [0,4) = 18, [0,8) = 37. Seven tasks are created in total; four of them are leaves.
If there were one more idle worker in the pool, it could have stolen the task [0,4) that entered the queue in step 2. In that case [0,4) and [4,8) would be computed truly in parallel, and the order in which tasks finish would change. The result would not change: every node is still the sum of its two children. This distinction comes up often in multithreaded programs: the execution order may not be deterministic, but the result of a correctly synchronized program is deterministic.
4.5.7OpenMP
OpenMP is a set of compiler directives and libraries that makes parallel programming easier on shared-memory systems for C, C++, and Fortran. The programmer marks the regions that can run in parallel with #pragma omp; the threads are created by the compiler and the OpenMP run-time.
#include <omp.h>
#include <stdio.h>
int main(void) {
#pragma omp parallel
printf("hello from %d\n", omp_get_thread_num());
double a[1000], b[1000], c[1000], s = 0;
/* ... fill in a and b ... */
#pragma omp parallel for reduction(+:s)
for (int i = 0; i < 1000; i++) {
c[i] = a[i] + b[i];
s += c[i];
}
return 0;
}#pragma omp parallel opens a parallel region: the statement that follows the directive runs separately in each member of a team of threads. The number of threads in the team defaults to the number of cores; it is changed with the OMP_NUM_THREADS environment variable or with num_threads(n) added to the directive. In this example the region is a single printf statement; each thread gets its own number with omp_get_thread_num() and prints a “hello” line. The order of the lines may change on every run. At the end of the region there is an implicit barrier: the program does not continue until all threads have finished.
The second directive, #pragma omp parallel for, divides the iterations of the for loop that follows among the threads. With four threads, each gets about 250 iterations. The line s += c[i] in the loop, however, is a problem: s is a single variable shared by all threads, and several threads adding to it at the same time creates a race condition. The reduction(+:s) clause solves this: each thread is given a private copy of s, and when the loop ends the copies are summed and added to the real s. The program is compiled with gcc -fopenmp; if this option is not given, the directives are ignored and the program runs sequentially.
4.5.8Grand Central Dispatch and oneTBB
Grand Central Dispatch (GCD) is the combination of a run-time library (libdispatch) developed by Apple for macOS and iOS and a language feature added to C and Objective-C. The language feature is blocks: self-contained units of work that begin with a caret and are written inside curly braces, like ^{ printf("I am a block"); }.
dispatch_queue_t q = dispatch_get_global_queue(
QOS_CLASS_USER_INITIATED, 0);
dispatch_async(q, ^{ puts("I am a block"); });Blocks are put on dispatch queues. A serial queue runs blocks in order, one at a time; every application’s main queue is serial, and user-interface work is done there. A concurrent (global) queue runs blocks in parallel. Global queues are divided into quality of service (QoS) classes; QOS_CLASS_USER_INITIATED in the example is for work that the user started and is waiting for. dispatch_async puts the block in the queue and returns at once. A block that leaves the queue is assigned to an idle thread in a system-managed pool. Thread management is entirely in GCD; the programmer creates no threads.
oneTBB is the open-source continuation of the Intel Threading Building Blocks library and comes as C++ templates. A call such as tbb::parallel_for(0, n, [&](int i) { f(v[i]); }); divides the range of the loop into pieces and distributes the pieces to threads with its own scheduler, using work stealing. The programmer only says “the iterations of this loop are independent of one another”; the library decides how many threads to use and how large the pieces are. In Apple’s Swift language, the language’s own async/await mechanism has largely taken the place of GCD.
4.6Thread issues
Many interfaces of the operating system were designed, before threads, on the assumption that every process has a single flow. fork(), signals, the global errno variable, and library functions that use static buffers are examples. When a process has several flows, a new question arises for each of these interfaces.
4.6.1fork() and exec() in a threaded process
In a process with three threads, if one of the threads calls fork(), how many threads should the child process have? Some UNIX systems gave two answers to this question and offered two versions of fork: one copied all the threads, the other only the caller. POSIX gives a single answer: only the thread that calls fork is copied. The whole address space is copied, but only one of the threads.
fork(). According to POSIX, the child process contains only a copy of T2 (T2′). A lock that T1 held at that moment may stay locked forever in the child.If exec is going to be called right after fork, this behavior is right: the new program replaces the whole address space anyway and starts with a single thread. Copying the other threads would be wasted work. The problem is the case where the child keeps running without calling exec. In the copied address space, the locks that the parent’s other threads held at the time of fork are also locked. For example, if T1 holds malloc’s internal lock at that moment, there is no T1 in the child to release this lock, and the child’s first malloc call waits forever.
For this reason, in the child of a multithreaded process POSIX allows only async-signal-safe functions (functions that can be called safely from a signal handler and use no internal locks) to be called until exec. pthread_atfork registers handlers that run before and after fork, which lets libraries bring their locks into an orderly state. If the goal is to start a new program, posix_spawn, which does fork and exec in a single step, is often the better choice.
4.6.2Signal handling
A signal is a software notification that tells a process an event has occurred. In a single-threaded process it is clear where the signal goes. In a multithreaded process, the question is: to which thread should the signal be delivered? There are four options, depending on the type of signal.
| Option | Example |
|---|---|
| To the thread the signal concerns | synchronous signals: SIGSEGV, SIGFPE |
| To every thread in the process | some termination cases |
| To any thread that does not block the signal | POSIX process signal: SIGINT |
| To a special thread that receives all signals | a sigwait loop |
Synchronous signals arise from an operation that a thread itself performs: an invalid memory access produces SIGSEGV, and division by zero produces SIGFPE. These signals naturally go to the thread that made the error. Asynchronous signals, on the other hand, come from outside: when the user presses Ctrl+C, the process receives SIGINT. POSIX delivers such a process signal to any thread that does not block that signal.
Two distinctions matter here. Signal handlers are process-wide: which function runs for a signal is the same for all threads. The signal mask, on the other hand, is private to the thread: each thread determines for itself which signals it blocks with pthread_sigmask. To send a signal to a specific thread, pthread_kill(tid, sig) is used.
SIGINT (Ctrl+C) arrives at the process. T1 and T2 have blocked the signal with their masks; the signal is delivered only to T3, which does not block it and waits with sigwait().Good practice in multithreaded programs is the arrangement in the figure. All threads block process signals; a single thread waits for these signals in a loop with sigwait. The signal is thus handled as an ordinary function return instead of an asynchronous handler, and the restrictions of the handler (only async-signal-safe functions) are avoided. None of these subtleties is possible with user-level threads: the kernel recognizes only the process and cannot address the right thread. Windows has no concept of signals; a similar task is performed by asynchronous procedure calls (APC).
4.6.3Thread cancellation
It may be necessary to terminate a thread before it finishes its work. When one of several threads searching in parallel in a database finds the result, the others become unnecessary. When the “stop” button is pressed in a browser, the threads that load the page must stop. The thread to be terminated is called the target thread. Cancellation takes two forms.
- Asynchronous cancellation
- The target is terminated immediately. The target may be holding a lock at that moment or may have half-updated a data structure; the lock is never released and the data is left inconsistent. It is therefore dangerous.
- Deferred cancellation (the default)
- The target checks for a cancellation request at certain cancellation points and, if there is a request, terminates in an orderly way.
main calls pthread_cancel(T); the request is held. When T reaches a cancellation point (read()), the cleanup handlers run (the lock is released, memory is returned), T terminates, and join returns PTHREAD_CANCELED.In deferred mode, pthread_cancel(T) is only a request; T keeps running. When T reaches a cancellation point, the request is processed. Cancellation points are calls specified by POSIX that can generally block: read, sleep, pthread_cond_wait, and the like. If a long computation loop never passes through a cancellation point, the programmer puts an artificial cancellation point in the loop by adding a pthread_testcancel() call. When the cancellation is processed, first the cleanup handlers registered with pthread_cleanup_push run, in the reverse order of registration: locks are released and allocated memory is returned. Then T terminates, and the thread waiting for it with join receives PTHREAD_CANCELED as the return value.
In Java the counterpart of cancellation is the cooperative interrupt() mechanism. t.interrupt() sets an interrupt flag on the target; the target checks the flag with Thread.interrupted() or leaves a blocking call with InterruptedException. Thread.stop(), the Java counterpart of asynchronous cancellation, has not worked since JDK 20 and throws an exception when called.
4.6.4Global variable conflicts
Global variables designed for single-threaded programs conflict between threads. The best-known example is UNIX’s errno variable. When a system call fails, it writes the error code into errno; after the call, the program reads this variable to learn the cause of the error.
errno conflict. Thread 1 calls access("file"), and errno = EACCES. The context changes; thread 2 calls open("x") and overwrites errno with ENOENT. When thread 1 runs again, it reads the wrong value (ENOENT).The problem has two solutions: forbid the variable or give each thread its own copy. The first is incompatible with old code; the second was therefore chosen. In today’s C libraries, errno is a macro and corresponds to a thread-local variable. Each thread sees its own errno.
4.6.5Thread-local storage
Thread-local storage (TLS) refers to variables that are accessed by the same name but have a separate copy in each thread. What one thread writes to a TLS variable, the other threads do not see.
The difference between TLS and a local variable is lifetime. A local variable lives only while the function in which it is defined runs, and other functions cannot access it. A TLS variable lives for the lifetime of the thread, across function calls: it is like a global variable, but private to the thread. It is defined with the keyword _Thread_local in C11, thread_local in C23 and C++, and __thread in GCC. Pthreads does the same job with function calls: pthread_key_create creates a key, and pthread_setspecific and pthread_getspecific write and read the value of that key in the calling thread. Typical uses are errno, the identifier of an operation, and a per-thread random number generator.
int err;: T1 and T2 share a single copy; the last writer wins. (b) _Thread_local int err;: the same name, a separate copy per thread; T1’s ENOENT and T2’s EACCES do not get mixed up.In Java, TLS is provided by the ThreadLocal class. The program below writes different values to the same ThreadLocal variable in two threads and at the end reads main’s own copy:
public class Local {
static ThreadLocal<Integer> id =
ThreadLocal.withInitial(() -> 0);
public static void main(String[] args) throws Exception {
Thread a = new Thread(() -> { id.set(1); System.out.println("A: " + id.get()); });
Thread b = new Thread(() -> { id.set(2); System.out.println("B: " + id.get()); });
a.start(); a.join();
b.start(); b.join();
System.out.println("main: " + id.get());
}
}ThreadLocal.withInitial(() -> 0) makes each thread’s copy start at 0 when it is first read. Thread A writes 1 to its own copy and thread B writes 2 to its own copy. When run with JDK 21, the output is A: 1, B: 2, main: 0. Because main writes nothing, it sees the initial value. Because A and B are run here in turn with join, the order of the lines is also the same every time; if the two threads were started together, the order of the A and B lines could vary, but the values would not.
4.6.6Reentrant and thread-safe code
Some library routines keep their internal state in static variables. Such a routine is called non-reentrant. If, while one thread puts a message into the library’s shared buffer, a context switch occurs and another thread writes to the same buffer, the first message is lost. malloc was historically like this too: while updating the free-memory list, it left the list briefly inconsistent, and an intervening thread could receive an invalid pointer. Today’s malloc implementations use internal locks and per-thread memory areas (arenas).
Thread-safe code can be called from several threads at the same time; it protects shared state with a lock or keeps no state at all. Reentrant code uses no shared state at all; all the state it needs is in the parameters given by the caller and in local variables.
Many functions of the classic C library have an unsafe version and a safe version added later. The safe versions usually end with the suffix _r (reentrant) and keep their state not in a static variable but in a pointer given by the caller.
| Unsafe | Safe version |
|---|---|
strtok | strtok_r |
localtime | localtime_r |
rand | rand_r or a local generator |
asctime, ctime | strftime |
Java SimpleDateFormat | DateTimeFormatter |
strtok’s static pointer. T1 starts splitting "a,b,c" and gets "a". T2 calls it with "x;y" and points the single-copy static char *last at its own string. T1’s next call strtok(NULL, ",") returns "y" instead of "b". In strtok_r this state is kept in the caller.strtok splits a string into pieces according to delimiters. The string is given on the first call; on later calls NULL is given and the function remembers where it left off from the static last pointer. In the scenario in the figure, T2’s call moves this pointer to its own string; T1 now gets not the rest of its own string but the "y" left over from T2’s string. strtok_r keeps the same pointer in a char ** parameter given by the caller; because each thread has its own pointer, there is no mix-up.
Treating the concepts of thread-safe and reentrant as synonyms. A function protected by a lock is thread-safe but not reentrant: if, while the same thread is inside the function, a signal handler calls the same function again, it may wait forever, because the thread itself already holds the lock. A reentrant function, which uses no shared state, is safe in both cases.
4.6.7Race condition: counter++
The simplest example of why access to shared data requires synchronization is incrementing a counter. In C or Java, counter++ is a single line, but on the machine it consists of three steps:
LOAD R, counter
ADD R, 1
STORE counter, RThe value is read from memory into a register (LOAD), incremented in the register (ADD), and written back to memory (STORE). If two threads execute these three steps interleaved, an increment can be lost.
A race condition is an erroneous situation in which several threads access shared data and the result depends on the timing of the accesses.
Let counter = 5 initially; T1 and T2 each increment the counter once. The expected result is 7. Table 4.18 traces an ordering in which an increment is lost.
| Step | T1 | T2 | R1 | R2 | counter |
|---|---|---|---|---|---|
| 1 | LOAD R1 ← counter | 5 | — | 5 | |
| 2 | LOAD R2 ← counter | 5 | 5 | 5 | |
| 3 | ADD R2, 1; STORE | 5 | 6 | 6 | |
| 4 | ADD R1, 1; STORE | 6 | 6 | 6 |
T1 reads the value into its register: R1 = 5. T2 steps in (through a context switch on a single core, or by running at the same time on multiple cores) and also reads 5. T2 increments and writes: counter = 6. T1 continues from its old value and writes 5 + 1 = 6. T2’s increment is lost; this bug is called a lost update. The four steps of the two threads can interleave in C(4, 2) = 6 different orders. When all the orderings are tried with Python, the result is 7 in two of them and 6 in four: when a thread gets in between the other’s read and write, the increment is lost.
pthread_mutex_lock or atomic_fetch_add, and in Java, synchronized or AtomicInteger is used.The solution is to make the read-increment-write sequence atomic: either the sequence is protected with a lock so that only one thread executes it at a time, or the hardware’s atomic operations that do read-modify-write in a single instruction are used. Locks, atomic instructions, and the critical-section problem are the subject of synchronization; what matters here is to see that the problem arises from the shared address space of threads.
The shared counter is 0. Three threads increment the counter once each; each increment has two steps: read (r = counter) and write (counter = r + 1). What are the possible final values?
- Largest value: If the threads run one after another, each reads what the previous one wrote: 0 → 1 → 2 → 3.
- Smallest value: If all three read before any writes, all three read 0 and all three write 1. The result is 1.
- Intermediate value: If two read the same value and the third reads after one of them has written, the result is 2.
- Counting. There are 6! / (2! · 2! · 2!) = 90 orderings in which the six steps can interleave. When all are tried with Python, 6 of them give 3, 36 give 2, and 48 give 1. The correct result, 3, is obtained in only 6.7% of the orderings.
4.6.8Observing the race
The lost update is not a theoretical possibility; it can be observed with a simple Java program. In the program below, two threads each increment the shared counter one million times.
public class Race {
static int counter = 0;
public static void main(String[] a) throws Exception {
Runnable job = () -> {
for (int i = 0; i < 1_000_000; i++) counter++;
};
Thread t1 = new Thread(job), t2 = new Thread(job);
t1.start(); t2.start();
t1.join(); t2.join();
System.out.println("counter = " + counter);
}
}The expected result is 2,000,000. When the program was run three times with JDK 21, the following results were obtained:
counter = 1456465
counter = 1544210
counter = 1910165When the same program was run five more times on another machine with JDK 21.0.3, the results were 1,024,058, 1,047,114, 1,929,112, 1,055,456, and 1,079,458. These numbers change on every run; even on the same machine, two runs do not give the same result. The only thing that does not change is that the result is smaller than 2,000,000 every time: some of the increments are lost.
The result is not deterministic: it depends on scheduling, the number of cores, and how the just-in-time (JIT) compiler compiles the code. The JIT can compile the loop so that the counter is kept in a register and the writes become sparser; this changes the number of lost increments. The output of such a program therefore cannot be traced step by step; only the range of possible values can be stated.
There are three ways to fix it. The increment can be put inside a synchronized block, AtomicInteger.incrementAndGet() can be used, or, for very heavy updates, LongAdder can be chosen. When the first two were tried with JDK 21, with two threads each doing one million increments, the output was every time:
synchronized: 2000000 atomic: 2000000The best solution is not to share at all: each thread counts in a local variable, and the results are combined at the end. This is the idea of fork-join and of the partial[k] example; the lock cost disappears too.
4.6.9Threads in Linux: clone()
The Linux kernel makes no distinction between a “process” and a “thread.” Both are a task and are represented by the same task_struct structure. A new task is created with the clone() system call; the flags given to clone() determine what the new task shares with its parent. If no sharing flag is given, the result is like fork: a copy of everything is made.
fork(): task B gets copies of the memory (mm), files, fs, and sighand structures. On the right, clone(CLONE_VM | CLONE_FILES | …): A and B point to the same structures.CLONE_VM shares the address space, CLONE_FS the file-system information such as the working directory and root directory, CLONE_FILES the open file table, and CLONE_SIGHAND the signal handlers. pthread_create corresponds roughly to the call clone(CLONE_VM | CLONE_FS | CLONE_FILES | CLONE_SIGHAND | CLONE_THREAD | …). CLONE_THREAD puts the new task in the same thread group as its parent. The group’s identifier (TGID, thread group ID) appears to the user as the process ID: getpid() returns the same value for everyone in the group. gettid() returns each task’s own identifier, that is, the thread ID. This flexibility lets Linux support processes, threads, and hybrid cases between the two (e.g., tasks that share memory but have separate file tables) with a single mechanism.
4.7Process or thread?
The advantages of threads are summarized as follows:
- Responsiveness: when one blocks, another handles user I/O.
- Resource sharing: memory, open files, and sockets are shared by default.
- Speed: creation and switching are cheaper than for processes.
- Hardware parallelism: a single process uses many cores.
- Easy programming model: parallelism is achieved even with blocking calls (the web server); each flow is written as sequential code.
The disadvantages are the other side of the same sharing:
- Synchronization: access to shared data must be controlled; there is a risk of races and deadlock.
- Dependence: threads in the same process are not independent; if one crashes, the whole process crashes.
- No memory protection: one thread can overwrite another’s stack.
- Debugging and testing are hard: bugs depend on timing and do not appear on every run.
The choice is made according to the balance between isolation and sharing. If isolation is needed, for example if browser tabs must not be affected by each other’s crashes or a security boundary must be drawn, a process is chosen. If tight data sharing and low cost are needed, a thread is chosen. Chrome uses both together: each tab and extension runs in a separate process, and inside each process there are several threads for drawing, networking, and script execution.
4.8Summary
- The process owns resources; the thread is a flow of execution inside a process and the basic unit of scheduling. The code, global data, heap, open files, and signal handlers are shared; the PC, registers, stack, state, signal mask, and TLS are private to each thread. The stack is private but not protected.
- Every thread has its own stack; on Linux the default size is usually 8 MiB, and the guard pages between stacks catch overflow with
SIGSEGV. - In a multithreaded web server, the dispatcher gives requests to workers; a worker that blocks on disk stops only itself. The gain comes, even on a single processor, from the overlap of waiting and computation. The event-driven design achieves the same overlap with a single thread but requires saving state by hand.
- Benefits: responsiveness, resource sharing, economy, scalability. In a switch between threads the address space does not change, and the TLB and cache stay warm.
- Concurrency is tasks progressing in the same time interval; parallelism is their execution at the same instant and requires at least two cores. Parallelism requires concurrency; the converse is not true.
- Amdahl’s law: speedup ≤ 1 / (S + (1 − S) / N); upper bound 1 / S. For S = 0.1 the speedup on 16 cores is 6.4× and the limit is 10×. Gustafson’s law gives the scaled speedup, when the problem grows, as S + (1 − S) · N.
- With user-level threads, switching is very cheap, but a blocking call and a page fault stop the whole process, the clock interrupt does not reach the library, and a single process cannot use several cores. Kernel-level threads block independently and run in parallel, but each uses kernel resources.
- N:1 is cheap but has no parallelism; 1:1 (Linux, Windows, macOS) provides true parallelism; M:N was abandoned in operating systems and has returned in language run-times (Go, Erlang, Java 21 virtual threads).
- Pthreads:
pthread_create,pthread_join,pthread_exit,pthread_detach. Arguments and results are passed asvoid *; the address given to a thread must live long enough, and the result must be returned on the heap. Java:start()starts a new thread,run()does not;joinboth waits and provides visibility. - Implicit threading: pools pay the creation cost once and bound the number of threads (for I/O-heavy work, Ncores × (1 + W / C)); fork-join splits the task and balances the load with work stealing; OpenMP works with compiler directives, GCD with blocks and queues, and oneTBB with templates.
- In POSIX,
fork()copies only the calling thread. Signal handlers are process-wide and the signal mask is private to the thread. With deferred cancellation, a thread terminates safely at cancellation points. Variables such aserrnoare made thread-private with TLS. counter++is the three steps read-increment-write; if unprotected, increments are lost and the result changes on every run. The solution is a lock, an atomic operation, or a design without sharing. On Linux, processes and threads are created with the sameclone()call, with different sharing flags.
4.9Key terms
- thread
- multithreaded process
- context switch
- concurrency
- parallelism
- false sharing
- Amdahl's law
- user-level / kernel-level thread
- thread pool
- work stealing
- signal
- thread-local storage
- reentrant / thread-safe
- race condition
- atomic instruction
4.10Test Yourself
Which of the following items are shared and which are private to each of two threads in the same process: the stack pointer, the open file table, a
staticvariable, a_Thread_localvariable, an array allocated on the heap withmalloc?Answer
Shared: the open file table, the
staticvariable, and the array on the heap; all three belong to the process’s address space or resources. Private: the stack pointer (each thread has its own stack) and the_Thread_localvariable (each thread has a separate copy).70% of a program can be parallelized. What are the speedup on four cores and the theoretical upper bound?
Answer
S = 0.3. On four cores the time is 0.3 + 0.7 / 4 = 0.3 + 0.175 = 0.475; the speedup is 1 / 0.475 ≈ 2.11×. The upper bound is 1 / 0.3 ≈ 3.33×.
Can a multithreaded program running on a single-core machine have a race condition? Why?
Answer
Yes. Even without parallelism there is concurrency. A thread’s time slice can end between
LOADandSTORE; the scheduler runs the other thread, which reads the same old value. A lost update also occurs on a single core; it is just seen less often.One of the threads of a program running in the N:1 model accesses a page that is not in memory. What happens? How does the same situation turn out in the 1:1 model?
Answer
In the N:1 model the page fault goes to the kernel, and while the kernel brings the page from disk it holds the process’s single kernel thread; the library cannot switch to another thread and the whole process stops. In the 1:1 model only the thread that caused the fault waits; the others keep running.
The array
a = {4, 1, 3, 5, 2, 6}is summed with the fork-joinSumTasktask withLIMIT = 2. Find the task tree and the result of each node.Answer
The root [0,6) splits: mid = 3. The left [0,3) has three elements and is larger than the limit; with mid = 1 it splits into [0,1) = 4 and [1,3) = 1 + 3 = 4, total 8. The right [3,6) splits too: [3,4) = 5 and [4,6) = 2 + 6 = 8, total 13. The root is 8 + 13 = 21. Seven tasks are created; four of them are leaves. (Run with a single-worker
ForkJoinPoolon JDK 21: 21.)On a four-core machine, each task computes for 10 ms and waits 30 ms for a database response. What does the rough rule give for the pool size? What would happen if the tasks only computed?
Answer
Nthreads ≈ 4 × (1 + 30 / 10) = 16. For tasks that only compute, the size should equal the number of cores, that is, 4; anything more only adds context switching and cache contention.
In a process with four threads, one thread calls
fork()and the child immediately callsexec("/bin/ls"). How many threads does the child have before and afterexec?Answer
One before
exec: in POSIX only the thread that callsforkis copied. One afterexecas well: the new program replaces the whole address space and starts with a single thread.Three threads each increment a counter that starts at 0 once, with an unprotected
counter++. What are the possible final values?Answer
1, 2, or 3. If all three read 0 before any writes, the result is 1; if two read the same value, 2; if there is no overlap at all, 3. Of the 90 possible orderings, 48 give 1, 36 give 2, and only 6 give 3.
A Java program, after the line
Thread t = new Thread(r);, callst.run();and never callsstart(). How many threads run, and what doest.getState()return?Answer
Only the
mainthread runs; the code ofrexecutes insidemainlike an ordinary method. Becausetwas never started,getState()returnsNEW.
4.11Further reading
- R. H. Arpaci-Dusseau and A. C. Arpaci-Dusseau, Operating Systems: Three Easy Pieces, the chapters “Concurrency: An Introduction” and “Interlude: Thread API”: they present race conditions and the Pthreads API with small, runnable C examples; free at ostep.org.
- A. S. Tanenbaum and H. Bos, Modern Operating Systems, Section 2.2: treats in detail the word processor, the web server, user-level and kernel-level threads, pop-up threads, and the problems of making single-threaded code multithreaded, which are the source of the examples in these notes.
- OpenJDK, JEP 444: Virtual Threads: the official document explains why virtual threads were designed, the mounting and unmounting mechanism, and in which cases they bring no gain.
- M. D. Hill and M. R. Marty, “Amdahl’s Law in the Multicore Era,” IEEE Computer, 41(7), 2008: extends Amdahl’s law to different core designs and shows how the serial part affects the design of multicore chips.
4.12References
- A. Silberschatz, P. B. Galvin, G. Gagne, Operating System Concepts, 10th edition, Wiley, 2018 — Chapter 4: Threads & Concurrency.
- A. S. Tanenbaum, H. Bos, Modern Operating Systems, 4th edition (2014) / 5th edition (2023), Pearson — Section 2.2: Threads.
- R. H. Arpaci-Dusseau, A. C. Arpaci-Dusseau, Operating Systems: Three Easy Pieces (OSTEP), ostep.org — “Concurrency: An Introduction”, “Thread API”.
- POSIX.1-2017 (IEEE Std 1003.1); the Linux manual pages
pthreads(7)andclone(2). - JEP 444: Virtual Threads (Java 21); the OpenMP 5.2 specification.
- G. M. Amdahl, “Validity of the single processor approach to achieving large scale computing capabilities”, AFIPS Spring Joint Computer Conference, 1967, pp. 483–485.
- J. L. Gustafson, “Reevaluating Amdahl’s Law”, Communications of the ACM, 31(5), 1988, pp. 532–533.
- M. D. Hill, M. R. Marty, “Amdahl’s Law in the Multicore Era”, IEEE Computer, 41(7), 2008, pp. 33–38.
Related pages: Chapter 4 slides · © Sercan Külcü. All rights reserved.