Notes
All notes

Processes and Threads (OS Core #2)

A process is a running program with its own address space. A thread is a stream of execution inside a process. The whole topic reduces to one question: what does each one own? Get that wrong and every question about shared data, context switches, and file descriptors becomes guesswork.

The process concept and its states

A process is more than the bytes of the executable. It is:

The kernel tracks a process through a small set of process states:

\begin{tikzpicture}[font=\rmfamily, >=stealth,
  b/.style={draw, thick, rounded corners=8pt, minimum width=1.7cm, minimum height=0.7cm, font=\scriptsize},
  a/.style={->, thick}]
  \node[b, fill=gray!12] (new) at (0,0) {new};
  \node[b, fill=green!18] (ready) at (2.4,0) {ready};
  \node[b, fill=orange!20] (run) at (4.8,0) {running};
  \node[b, fill=blue!15] (wait) at (2.4,-1.5) {blocked};
  \node[b, fill=red!12] (term) at (7.2,0) {terminated};
  \draw[a] (new) -- (ready);
  \draw[a] (ready) -- node[above, font=\tiny] {dispatch} (run);
  \draw[a] (run) to[bend left=18] node[above, font=\tiny] {preempt} (ready);
  \draw[a] (run) -- node[right, font=\tiny] {wait for I/O} (wait);
  \draw[a] (wait) -- node[left, font=\tiny] {I/O done} (ready);
  \draw[a] (run) -- node[above, font=\tiny] {exit} (term);
\end{tikzpicture}

Linux shows these in ps as R (running/runnable), S (interruptible sleep), D (uninterruptible sleep, usually I/O), T (stopped), Z (zombie).

A process does not go from blocked to running directly. It becomes ready, then the scheduler picks it. That distinction is why a busy machine can have many runnable processes and only a few running ones.

QQuestionA process is in D state and kill -9 does nothing. Why?
ASolution

D is uninterruptible sleep, usually waiting on I/O in the kernel. Signals are delivered only when the process returns to user mode, so it cannot be killed until the I/O finishes or times out.

Process Control Block

The PCB is the kernel’s data structure for a process. It contains everything the kernel needs when the process is not running.

Field Purpose
pid, ppid identity and parent
state ready, running, blocked
program counter, registers resume point
memory map page tables, segments
open file table descriptors
scheduling info priority, CPU time, nice
accounting start time, usage
signal state pending, blocked, handlers
credentials uid, gid, capabilities

In Linux the PCB is struct task_struct, a few kilobytes in size, allocated in kernel memory. The kernel stack is attached to it (16 KB on x86-64 with 4 KB pages).

The PCB is what makes a context switch possible: save the current process’s registers into its PCB, load the next one’s.

QQuestionWhere does the PCB live: user space or kernel space?
ASolution

Kernel space. User code cannot read or modify it directly; it can only observe parts of it through /proc and syscalls.

Thread Control Block

A thread is a schedulable execution context. Its TCB is smaller than a PCB and holds only the per-thread state:

In Linux, threads are tasks created with clone() sharing the address space, file table, and signal handlers. The kernel uses the same task_struct for both; what differs is which resources are shared.

#include <pthread.h>
pthread_t t;
pthread_create(&t, nullptr, worker, arg);   // shares address space
pthread_join(t, nullptr);
QQuestionWhy does a thread need its own kernel stack?
ASolution

If the thread blocks in a syscall, the kernel must keep that thread’s kernel execution state somewhere. Each thread gets a kernel stack so another thread can run meanwhile.

Process creation and termination

On Unix, a new process is made in two steps: fork duplicates the current process, and exec replaces its image.

#include <unistd.h>
#include <sys/wait.h>
#include <cstdio>

int main() {
    pid_t pid = fork();
    if (pid == 0) {
        // child
        execlp("echo", "echo", "hello from child", (char*)nullptr);
        _exit(127);                  // exec failed
    } else if (pid > 0) {
        int status = 0;
        waitpid(pid, &status, 0);    // reap the child
        if (WIFEXITED(status))
            std::printf("child exited with %d\n", WEXITSTATUS(status));
    } else {
        std::perror("fork");
    }
}

fork returns twice: 0 in the child, the child’s pid in the parent, -1 on failure. The child gets a copy of the address space, but the pages are marked copy-on-write, so the copy is cheap until someone writes.

exec replaces the process image but keeps the pid, open file descriptors (unless marked close-on-exec), and credentials. That is why a shell can fork and then exec a command and still be the same process from the terminal’s point of view.

Termination:

Zombies take a slot in the process table. A server that forks and never waits accumulates them until it hits the pid limit.

QQuestionWhy is fork in a multithreaded program dangerous?
ASolution

Only the calling thread survives in the child, but locks held by other threads are copied in their locked state. The child can deadlock on a lock no one will release. Between fork and exec, only async-signal-safe functions are safe.

Threads versus processes

Resource Process Thread
Address space private shared
Code, global data, heap private (COW after fork) shared
Stack private private
Registers, PC private private
Open file descriptors private table (shared after fork) shared
Working directory private shared
Signal handlers private shared
Signal mask private private
TLS, errno per process/thread per thread
Creation cost ~100–500 µs ~10–50 µs
Context switch ~2–10 µs ~1–5 µs
Isolation strong (MMU) none

A thread crash (segfault, abort) kills the whole process, because the address space is shared. That is the trade: threads are cheap and share data easily, but they have no fault isolation.

QQuestionTwo threads in one process each declare int counter = 0; as a local

variable. Do they share it?

ASolution

No. Locals live on each thread’s own stack. Sharing requires a global, a heap allocation, or a captured reference.

User-level and kernel-level threads

A kernel-level thread is scheduled by the kernel and can run on any core. A user-level thread is managed by a library in user space; the kernel sees only the underlying kernel thread(s).

Model Mapping Example Blocking syscall
Many-to-one many ULTs on one KLT early green threads blocks all threads
One-to-one one ULT per KLT Linux pthreads, Windows blocks only that thread
Many-to-many ULTs multiplexed on a pool of KLTs Go scheduler, Erlang handled by runtime

Linux uses one-to-one: pthread_create creates a kernel task. Go uses a many-to-many scheduler with G (goroutine), M (OS thread), and P (processor) structures, which is why a Go program can have a million goroutines but only a few thousand OS threads.

User-level threads are cheap to create and switch (a function call), but a blocking syscall in a many-to-one design stops everything. The runtime fixes that by making syscalls non-blocking and parking the goroutine.

QQuestionWhy can a many-to-one thread library not use multiple cores?
ASolution

The kernel schedules the single underlying thread on one core. User-level threads take turns inside it, so they are concurrent but not parallel.

Multithreading

Threads help when work can be split or when a program must wait for several things at once.

The limit is Amdahl’s law. If a fraction \(p\) of the work is parallelizable and the rest is serial:

\[ \text{speedup}(N) = \frac{1}{(1-p) + p/N} \]

With \(p = 0.95\) and 16 cores, the best speedup is about 9.4×, not 16×. With \(p = 0.5\), it is under 2× no matter how many cores you buy.

Threads also add costs: synchronization, cache contention, and bugs. A single thread with a good algorithm often beats eight threads fighting over a lock.

QQuestionA program has a serial section that is 10% of the runtime. What is

the maximum speedup with unlimited cores?

ASolution

\(1/0.1 = 10\times\). The serial part dominates no matter how many cores are added.

Context switching

A context switch saves one execution context and restores another.

  1. Trap into the kernel (timer interrupt or blocking syscall).
  2. Save the current thread’s registers into its PCB/TCB.
  3. Run the scheduler to pick the next thread.
  4. Switch page tables if the next thread is in a different process (this flushes TLB entries unless the CPU tags them by address space).
  5. Restore the next thread’s registers and return to user mode.

The direct cost is about 1–10 µs. The indirect cost is often larger: cold caches, TLB misses, and branch-predictor state after the switch. A server that switches every 100 µs can spend 10% of its CPU on switching alone.

A mode switch (syscall) does not change the thread. A context switch changes the running thread. Confusing the two is a common interview mistake.

QQuestionWhy is a context switch between threads of the same process cheaper

than between different processes?

ASolution

The page tables stay the same, so the TLB does not need to be flushed and the memory mapping does not change.

Thread-local storage

TLS gives each thread its own copy of a variable. errno is the classic example: two threads failing at the same time must not overwrite each other’s error code.

thread_local int counter = 0;      // one per thread

void worker() {
    ++counter;                     // independent in each thread
}

The compiler implements TLS through a per-thread block addressed by a dedicated register (fs on x86-64 Linux). Access is a few instructions, slightly slower than a normal global but far cheaper than a lock.

TLS is initialized per thread: a thread_local with a constructor runs it on first use in each thread. Destruction happens at thread exit.

QQuestionIs a static local variable inside a function thread-safe?
ASolution

The variable is shared by all threads, and its initialization is thread-safe since C++11, but the variable itself is not protected. Concurrent writes are a data race. Use thread_local if each thread needs its own copy.

Process memory layout

A process’s virtual address space is divided into regions with different permissions and lifetimes. Details are in Ch. 6; the shape matters here because threads share all of it except the stacks.

\begin{tikzpicture}[font=\rmfamily, >=stealth,
  r/.style={draw, thick, minimum width=3.6cm, minimum height=0.55cm, font=\scriptsize}]
  \node[r, fill=gray!8] (k) at (0,3.2) {kernel (not accessible)};
  \node[r, fill=green!15] (s) at (0,2.5) {stack (grows down)};
  \node[r, fill=gray!5] (g) at (0,1.85) {guard page};
  \node[r, fill=orange!15] (h) at (0,1.2) {heap (grows up)};
  \node[r, fill=blue!12] (b) at (0,0.55) {BSS (zero-initialized)};
  \node[r, fill=blue!12] (d) at (0,-0.1) {data (initialized)};
  \node[r, fill=blue!12] (t) at (0,-0.75) {text (code, read-only)};
  \draw[->, thick] (1.95,1.2) -- (2.35,1.2);
  \draw[->, thick] (1.95,2.5) -- (2.35,2.5);
  \node[font=\scriptsize, anchor=west] at (2.45,1.2) {mmap, malloc};
  \node[font=\scriptsize, anchor=west] at (2.45,2.5) {thread stacks};
\end{tikzpicture}

Each thread gets its own stack region inside this space. The heap, globals, and code are shared, which is exactly why a thread can corrupt another thread’s data with a stray pointer.

QQuestionWhy is the stack usually limited to a few megabytes while the heap

can grow to gigabytes?

ASolution

The stack is a fixed reservation per thread (8 MB default on Linux), and large stacks multiplied by many threads waste address space. The heap grows on demand in page-sized chunks.

File descriptors and resource inheritance

A file descriptor is an index into a per-process table. The entry points to a system-wide open file description, which holds the file offset and flags.

int fd = open("log.txt", O_WRONLY | O_CREAT | O_APPEND, 0644);
pid_t pid = fork();
if (pid == 0) {
    write(fd, "child\n", 6);     // same open file description
    _exit(0);
}
write(fd, "parent\n", 6);        // shares the offset with the child

After fork, parent and child share the open file description, so their writes share one offset. After exec, descriptors stay open unless they were marked FD_CLOEXEC, which is why shells can redirect stdin/stdout by reopening fds 0 and 1 before exec.

int fd = open("secret.txt", O_RDONLY | O_CLOEXEC);

O_CLOEXEC closes the descriptor on exec, preventing leaks into unrelated programs. It is the default habit for every descriptor you do not intend to pass on.

QQuestionA parent opens a file, forks, and both write 100 bytes. How many

bytes are in the file?

ASolution

200 bytes at two different offsets, because both share the same open file description and therefore the same advancing offset. If each opened the file separately, they would overwrite each other at offset 0.

Deep: what threads share

This is the table to memorise.

Shared between threads Private to each thread
code (text) registers, program counter
global and static data stack and stack pointer
heap (new, malloc) thread-local storage
open file descriptors signal mask
current working directory errno
signal handlers thread id
environment scheduling priority, affinity
address space and page tables pending signals (per thread)
#include <thread>
#include <cstdio>

int shared = 0;
thread_local int local = 0;

void worker(int id) {
    ++shared;          // data race without synchronization
    ++local;           // no race: one copy per thread
    std::printf("thread %d: shared=%d local=%d\n", id, shared, local);
}

int main() {
    std::thread a(worker, 1), b(worker, 2);
    a.join(); b.join();
}

The two ++shared operations are a race; the output values of shared are not predictable. local is always 1 in each thread.

fork versus thread in one line: a thread shares everything except its execution state; a process shares nothing except through explicit IPC.

QQuestionThread A opens a file and gets fd 3. Thread B calls read(3, ...).

Does it read from the same open file description?

ASolution

Yes. Threads share the descriptor table, so fd 3 in B is the same entry as fd 3 in A, with the same offset and flags. Closing it in one thread closes it for both.

Bugs and edge cases

QQuestionA multithreaded server occasionally hangs after fork. What is the

likely cause?

ASolution

A lock was held by another thread at the moment of fork. The child inherits it locked, with no thread able to release it. Avoid fork in threaded code, or only call async-signal-safe functions and exec immediately.

Next: CPU Scheduling (OS Core #3) — FCFS, SJF, round robin, and how to compute waiting and turnaround times.