Lesson 4 · Processes, threads, and CPU scheduling

Multithreading Models

A multithreading model is the mapping between user threads, which programs create, and kernel threads, which the OS schedules. The mapping decides whether threads run in parallel and what a blocking call stops.

Multithreading Models concept diagramFour panels. Many-to-one: four user threads all mapped to one kernel thread. One-to-one: three user threads, each mapped to its own kernel thread. Many-to-many: four user threads multiplexed onto two kernel threads. Two-level: three user threads multiplexed onto two kernel threads plus one user thread bound to its own kernel thread. A dashed line separates user space from kernel space.userkernelmany-to-oneUUUUKcheap switchesone block stops allone-to-oneUUUKKKtrue parallelisma kernel thread eachmany-to-manyUUUUKKparallel on N threadscomplex to implementtwo-levelUUUUKKKM:N plus boundbound thread = 1:1the kernel schedules only kernel threads; the thread library maps user threads onto them
1

User Threads, Kernel Threads and the Mapping

  1. Many-to-one – many user threads mapped to a single kernel thread.
  2. One-to-one – each user thread mapped to its own kernel thread.
  3. Many-to-many – many user threads multiplexed onto a smaller or equal number of kernel threads.
  4. Two-level – many-to-many, but a user thread may also be bound to its own kernel thread.

Threads exist at two levels. User threads are created and managed by a thread library in user space, such as POSIX Pthreads, Java threads or a language runtime. Kernel threads are created and scheduled by the operating system itself; only they can be given a CPU.

A multithreading model is the relationship between the two: how many user threads are mapped onto how many kernel threads. The choice determines three things every exam answer should mention: whether threads of one process can run in parallel on several CPUs, what happens when one thread makes a blocking system call, and how expensive it is to create and switch threads.

  • The kernel schedules kernel threads; the library maps user threads onto them
  • Parallelism is limited by the number of usable kernel threads
  • A blocking system call blocks the kernel thread it was made on
2

User-Level Threads vs Kernel-Level Threads

The models trade off the properties of the two kinds of thread. User-level threads are fast because creating, switching and synchronising them needs no system call: it is a function call and a register swap inside the process. But the kernel does not know they exist. Kernel-level threads are known to the kernel, so it can schedule them on different CPUs and block them individually, but each operation involves a trap into the kernel.

User-level against kernel-level threads
AspectUser-level threadsKernel-level threads
Managed bya thread library in user spacethe operating system kernel
Kernel aware of them?no, it sees only the processyes, each is scheduled individually
Creation and switch costlow: no system callhigher: a trap into the kernel
Blocking system callblocks every thread on that kernel threadblocks only the calling thread
Run on several CPUs?only through several kernel threadsyes
ExamplesGNU Portable Threads, green threads, goroutinesLinux tasks, Windows threads
  • User-level: fast and portable, blind to the kernel
  • Kernel-level: parallel and independently blocking, heavier
  • Every model is a way of combining the two
3

Many-to-One Model

In the many-to-one model, all the user threads of a process are mapped onto one kernel thread. Thread management is done entirely by the library in user space, so it is efficient, and it works even on a kernel with no thread support at all.

It has two serious drawbacks. Because the kernel sees a single thread, it can run it on only one CPU at a time, so the threads never execute in parallel on a multicore system. And if any thread makes a blocking system call, the one kernel thread blocks, and with it every thread in the process. The tracer below shows both.

  • Plus – the library can use any scheduling policy it likes
  • Minus – the kernel cannot schedule the threads fairly against other processes
  • Examples: Solaris Green Threads, early Java green threads, GNU Portable Threads
  • Rarely used today because multicore CPUs are universal
Key reference

Terms, operations, and practical uses

Core vocabulary

  • User threadA thread managed by a user-space library, invisible to the kernel.
  • Kernel threadA thread the OS schedules; the only kind that can own a CPU.
  • LWPLightweight process: the kernel thread a many-to-many library runs user threads on.
  • Bound threadA user thread permanently attached to its own kernel thread.

Mechanisms

  • Blocking callBlocks the kernel thread it is made on, and every user thread mapped only to it.
  • Scheduler activationsKernel upcalls that give the library a new kernel thread when one blocks.
  • NPTLNative POSIX Thread Library: Linux's one-to-one Pthreads since 2003.
  • Virtual threadsJava 21's many-to-many threads, run on a pool of carrier threads.
Implementation

One blocking call under three threading models

from collections import deque

CPUS = 2
WORK = 3  # ticks of CPU each user thread needs
IO_TICKS = 3  # U2 blocks in read() for this long after its first tick
THREADS = ["U1", "U2", "U3", "U4"]


def simulate(kernel_threads):
    # A user thread blocked in a system call pins the kernel thread it runs on,
    # so only the remaining kernel threads can be given a CPU.
    ready = deque(THREADS)
    left = {u: WORK for u in THREADS}
    wake_at = {}
    lanes = [[] for _ in range(CPUS)]
    t = 0
    while any(left.values()):
        for u in [u for u, when in wake_at.items() if when == t]:
            del wake_at[u]
            ready.append(u)
        usable = min(CPUS, kernel_threads - len(wake_at))
        running = [ready.popleft() for _ in range(min(usable, len(ready)))]
        for cpu in range(CPUS):
            lanes[cpu].append(running[cpu] if cpu < len(running) else "--")
        for u in running:
            left[u] -= 1
            if u == "U2" and left[u] == WORK - 1:
                wake_at[u] = t + 1 + IO_TICKS  # the blocking read() starts
            elif left[u]:
                ready.append(u)  # quantum over: back of the user-level queue
        t += 1
    return lanes, t


MODELS = [("many-to-one", 1), ("one-to-one", 4), ("many-to-many", 2)]
for name, kernel_threads in MODELS:
    lanes, finish = simulate(kernel_threads)
    plural = "s" if kernel_threads > 1 else ""
    print(f"{name}: 4 user threads on {kernel_threads} kernel thread{plural}")
    for cpu, lane in enumerate(lanes):
        print(f"  CPU {cpu}: {' '.join(lane)}")
    print(f"  all done at t = {finish}")
#include <algorithm>
#include <cstdio>
#include <deque>
#include <map>
#include <string>
#include <vector>
using namespace std;

const int CPUS = 2;
const int WORK = 3;      // ticks of CPU each user thread needs
const int IO_TICKS = 3;  // U2 blocks in read() for this long after its first tick
const vector<string> THREADS = {"U1", "U2", "U3", "U4"};

// A user thread blocked in a system call pins the kernel thread it runs on,
// so only the remaining kernel threads can be given a CPU.
int simulate(int kernelThreads, vector<vector<string>>& lanes) {
    deque<string> ready(THREADS.begin(), THREADS.end());
    map<string, int> left, wakeAt;
    for (const string& u : THREADS) left[u] = WORK;
    lanes.assign(CPUS, {});
    int t = 0, remaining = THREADS.size() * WORK;
    while (remaining > 0) {
        for (auto it = wakeAt.begin(); it != wakeAt.end();) {
            if (it->second == t) {
                ready.push_back(it->first);
                it = wakeAt.erase(it);
            } else {
                ++it;
            }
        }
        int usable = min(CPUS, kernelThreads - (int)wakeAt.size());
        vector<string> running;
        while ((int)running.size() < usable && !ready.empty()) {
            running.push_back(ready.front());
            ready.pop_front();
        }
        for (int cpu = 0; cpu < CPUS; cpu++) {
            lanes[cpu].push_back(cpu < (int)running.size() ? running[cpu] : "--");
        }
        for (const string& u : running) {
            left[u]--;
            remaining--;
            if (u == "U2" && left[u] == WORK - 1) {
                wakeAt[u] = t + 1 + IO_TICKS;  // the blocking read() starts
            } else if (left[u] > 0) {
                ready.push_back(u);  // quantum over: back of the user-level queue
            }
        }
        t++;
    }
    return t;
}

int main() {
    vector<pair<string, int>> models = {{"many-to-one", 1}, {"one-to-one", 4}, {"many-to-many", 2}};
    for (const auto& [name, kernelThreads] : models) {
        vector<vector<string>> lanes;
        int finish = simulate(kernelThreads, lanes);
        const char* plural = kernelThreads > 1 ? "s" : "";
        printf("%s: 4 user threads on %d kernel thread%s\n", name.c_str(), kernelThreads, plural);
        for (int cpu = 0; cpu < CPUS; cpu++) {
            printf("  CPU %d:", cpu);
            for (const string& s : lanes[cpu]) printf(" %s", s.c_str());
            printf("\n");
        }
        printf("  all done at t = %d\n", finish);
    }
    return 0;
}
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Deque;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

public class Main {
    static final int CPUS = 2;
    static final int WORK = 3; // ticks of CPU each user thread needs
    static final int IO_TICKS = 3; // U2 blocks in read() for this long after its first tick
    static final String[] THREADS = {"U1", "U2", "U3", "U4"};

    // A user thread blocked in a system call pins the kernel thread it runs on,
    // so only the remaining kernel threads can be given a CPU.
    static int simulate(int kernelThreads, List<List<String>> lanes) {
        Deque<String> ready = new ArrayDeque<>(List.of(THREADS));
        Map<String, Integer> left = new LinkedHashMap<>();
        Map<String, Integer> wakeAt = new LinkedHashMap<>();
        for (String u : THREADS) left.put(u, WORK);
        for (int cpu = 0; cpu < CPUS; cpu++) lanes.add(new ArrayList<>());
        int t = 0, remaining = THREADS.length * WORK;
        while (remaining > 0) {
            final int now = t;
            wakeAt.entrySet().removeIf(e -> {
                if (e.getValue() != now) return false;
                ready.addLast(e.getKey());
                return true;
            });
            int usable = Math.min(CPUS, kernelThreads - wakeAt.size());
            List<String> running = new ArrayList<>();
            while (running.size() < usable && !ready.isEmpty()) running.add(ready.pollFirst());
            for (int cpu = 0; cpu < CPUS; cpu++) {
                lanes.get(cpu).add(cpu < running.size() ? running.get(cpu) : "--");
            }
            for (String u : running) {
                left.merge(u, -1, Integer::sum);
                remaining--;
                if (u.equals("U2") && left.get(u) == WORK - 1) {
                    wakeAt.put(u, t + 1 + IO_TICKS); // the blocking read() starts
                } else if (left.get(u) > 0) {
                    ready.addLast(u); // quantum over: back of the user-level queue
                }
            }
            t++;
        }
        return t;
    }

    public static void main(String[] args) {
        String[] names = {"many-to-one", "one-to-one", "many-to-many"};
        int[] kernel = {1, 4, 2};
        for (int m = 0; m < names.length; m++) {
            List<List<String>> lanes = new ArrayList<>();
            int finish = simulate(kernel[m], lanes);
            String plural = kernel[m] > 1 ? "s" : "";
            System.out.printf("%s: 4 user threads on %d kernel thread%s%n", names[m], kernel[m], plural);
            for (int cpu = 0; cpu < CPUS; cpu++) {
                System.out.printf("  CPU %d: %s%n", cpu, String.join(" ", lanes.get(cpu)));
            }
            System.out.printf("  all done at t = %d%n", finish);
        }
    }
}
Watch it run

Step through it

Running on U1–U4 need 3 ticks each; 2 CPUs; U2 blocks in read() for 3 ticks after its first tick

many-to-one: 4 user threads on 1 kernel threaduserkernelU1U2U3U4K1CPU 0—CPU 1no kernel threadCPU timelineCPU 0CPU 1U2 read()0123456789101112131415all threads finished atmany-to-one?one-to-one?many-to-many?
Step 1

Many-to-one: all four user threads share one kernel thread

A user-level thread library schedules U1–U4 itself; the kernel sees only one thread, K1. Switching between user threads is cheap because no system call is needed. But the kernel can put K1 on only one CPU, so CPU 1 has nothing it could run.

Output
1 / 16
4

One-to-One Model

In the one-to-one model, every user thread is mapped to its own kernel thread. Creating a user thread creates a kernel thread with it. Because the kernel schedules each thread, threads of one process can run in parallel on multiple CPUs, and a blocking call blocks only the thread that made it.

The drawback is cost. Every thread needs a kernel thread, with its own kernel stack and data structures, and creation is a system call. Systems therefore limit the number of threads per process, and programs that need thousands of concurrent tasks use a thread pool instead of a thread per task.

  • Plus – simple: the kernel scheduler does all the work
  • Minus – thread switches go through the kernel
  • Examples: Linux (NPTL Pthreads), Windows, macOS, Java platform threads
  • The dominant model on general-purpose operating systems
5

Many-to-Many Model

The many-to-many model multiplexes M user threads onto N kernel threads, where N ≤ M, often N equal to the number of CPUs. The program can create as many user threads as it likes, cheaply, and they still run in parallel on up to N CPUs. When a thread blocks, the library runs another user thread on a different kernel thread.

Its weakness is visible in the tracer: a blocked thread still pins its kernel thread, so with few kernel threads, parallelism drops while calls are in progress. The fix, scheduler activations, has the kernel notify the library through an upcall when a kernel thread is about to block, and give it a new kernel thread (a lightweight process, or LWP) to keep running other user threads. The coordination is complex, which is why most operating systems abandoned the model.

  • Minus – the kernel and library can make conflicting scheduling decisions
  • Examples: Solaris before version 9, Windows with the ThreadFiber package
  • LWP: the kernel thread a user thread library runs its threads on
6

Two-Level Model

The two-level model is a variation of many-to-many that also allows a user thread to be bound to a kernel thread. Unbound threads are multiplexed as in many-to-many; a bound thread has a kernel thread to itself, as in one-to-one, and is scheduled directly by the kernel.

Binding is useful for a thread that must respond quickly or has real-time requirements, because it never waits for the library to give it a kernel thread. The highlighted thread in the diagram's fourth panel is bound.

  • Unbound threads: many-to-many
  • Bound threads: one-to-one, for latency-sensitive work
  • Examples: IRIX, HP-UX, Tru64 UNIX, Solaris 8 and earlier
7

The Four Models Compared

The tracer's numbers summarise the comparison: the same work took 15 ticks under many-to-one, 7 under one-to-one and 8 under many-to-many. The difference comes almost entirely from how each model handles a blocking system call and how many CPUs it can use.

The four models side by side
ModelMappingParallelismBlocking call stopsThread creation costExamples
Many-to-oneM : 1noneevery threadlowestGreen Threads, GNU Portable Threads
One-to-one1 : 1fullonly the callerhighestLinux, Windows, macOS
Many-to-manyM : Nup to Nthe caller and its kernel threadlowSolaris ≤ 8, ThreadFiber
Two-levelM : N + 1 : 1up to N + boundas many-to-many; bound threads as 1:1low / highIRIX, HP-UX, Tru64
  • Need parallelism: avoid many-to-one
  • Need very many threads: many-to-many or a pool on one-to-one
  • Need simplicity: one-to-one
8

What Modern Systems Use

At the operating-system level, one-to-one won. Linux replaced LinuxThreads with NPTL, a one-to-one implementation, in 2003; Windows and macOS have always used one-to-one; Solaris switched from many-to-many to one-to-one in version 9. Kernel threads became cheap enough that the extra complexity of many-to-many was no longer worth it.

Many-to-many has returned one level higher, inside language runtimes. Go schedules millions of goroutines onto a few OS threads; Java 21's virtual threads run on a small pool of carrier threads; Erlang processes and Rust's async executors work the same way. They avoid many-to-many's old weakness by intercepting blocking calls and turning them into non-blocking ones, so a waiting task never pins an OS thread.

  • OS threads: one-to-one on Linux, Windows and macOS
  • Runtime threads: many-to-many in Go, Java virtual threads, Erlang
  • See Processes and Threads for what a thread holds