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:
- an address space (code, data, heap, stack, shared libraries),
- registers and a program counter,
- open file descriptors and other kernel resources,
- credentials (uid, gid), a working directory, an environment,
- signals pending and blocked.
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}
- new: being created.
- ready: runnable, waiting for a CPU.
- running: executing on a CPU.
- blocked (waiting): cannot run until an event happens (I/O, lock, sleep).
- terminated: exited, resources being reclaimed.
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.
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.
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:
- saved registers and program counter,
- stack pointer and stack (user and kernel),
- thread id (tid),
- thread-local storage pointer,
- signal mask,
- scheduling parameters (priority, affinity).
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);
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:
exit(status)runsatexithandlers and flushes stdio, then calls_exit._exit(status)goes straight to the kernel.- The kernel keeps the exit status until the parent calls
wait/waitpid. - A child that has exited but not been waited for is a zombie.
- A child whose parent died is an orphan, reparented to
init/systemd.
Zombies take a slot in the process table. A server that forks and never waits accumulates them until it hits the pid limit.
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.
int counter = 0; as a localvariable. 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.
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.
- Parallelism: CPU-bound work on multiple cores.
- Latency hiding: one thread blocks on I/O while others compute.
- Responsiveness: a UI thread stays alive while a worker runs.
- Resource sharing: threads share memory without IPC.
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.
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.
- Trap into the kernel (timer interrupt or blocking syscall).
- Save the current thread’s registers into its PCB/TCB.
- Run the scheduler to pick the next thread.
- Switch page tables if the next thread is in a different process (this flushes TLB entries unless the CPU tags them by address space).
- 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.
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.
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.
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.
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.
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
- Forking with locks held. The child inherits locked mutexes with no owner
thread. Use
pthread_atforkorexecimmediately. - Zombie accumulation. Every
forkneeds await; useSIGCHLDor double-fork. - Assuming
forkcopies eagerly. It does not; copy-on-write means writes after fork allocate new pages. - Thread stack overflow. Deep recursion in a thread with a small stack
segfaults; set the stack size with
pthread_attr_setstacksize. - Descriptor leaks. Missing
close, or missingO_CLOEXEC, leaks into child programs. exitin a thread. It terminates the whole process; usepthread_exitor return from the thread function.- Shared data without a lock. Any non-atomic write read by another thread is a data race, and the result is undefined.
fork. What is thelikely 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.