Threads
A process is a container of resources. A thread is a path of execution inside it: an instruction pointer, a set of CPU registers and a stack. Every process starts with one thread; it can create more, and they all share the process's memory, open files and identity. The CPU scheduler works on threads, not on processes.
process (one address space, one fd/handle table)
+---------------------------------------------------------+
| code global data heap (shared by everyone) |
| |
| thread 1 thread 2 thread 3 |
| [regs, IP] [regs, IP] [regs, IP] |
| [stack 1] [stack 2] [stack 3] |
| [TLS] [TLS] [TLS] |
+---------------------------------------------------------+Each thread has its own stack (local variables, return addresses) and thread-local storage (TLS), but a global variable or a heap object written by one thread is immediately visible to all the others. That sharing is what makes threads fast to communicate, and what makes them dangerous (see Synchronization & Deadlocks).
Why threads?
| Use | Example |
|---|---|
| Use several CPU cores | A video encoder splits a frame into strips, one thread per core |
| Keep a UI responsive | A GUI thread handles clicks while a worker thread downloads a file |
| Overlap waiting | A server thread blocks on one client's socket while others keep serving |
| Cheaper than processes | Creating a thread skips building a new address space and handle table |
The price: a bug in one thread (a wild pointer, an unhandled exception) takes down the whole process, and shared data needs locking. Browsers such as Chrome deliberately use processes for tabs to get isolation instead.
Threads on Linux and Windows
Linux has no separate "thread" object in the kernel. Everything is a task. The clone() system call creates
a task and takes flags saying what to share with the parent: CLONE_VM (memory), CLONE_FILES (descriptors),
CLONE_SIGHAND, CLONE_THREAD and so on. fork() is roughly clone() sharing nothing; pthread_create() from
glibc calls clone() sharing almost everything. The threads of a process form a thread group: getpid() returns
the group ID (the first thread's ID) for all of them, and gettid() returns each thread's own ID.
Windows has distinct kernel objects: a process (EPROCESS) owns one or more threads (ETHREAD), created with
CreateThread() (or _beginthreadex in the C runtime, std::thread, .NET Thread/Task). A process with zero
threads ends. Thread IDs and process IDs come from the same pool of numbers.
| Linux | Windows | |
|---|---|---|
| Create | pthread_create() → clone(CLONE_VM | CLONE_THREAD …) |
CreateThread() / _beginthreadex() |
| Wait for a thread | pthread_join() |
WaitForSingleObject(hThread) |
| Own ID | gettid() |
GetCurrentThreadId() |
| Default stack size | 8 MiB (from ulimit -s) |
1 MiB (from the EXE header) |
| Thread-local storage | __thread / thread_local, pthread_key_create |
TlsAlloc, __declspec(thread), thread_local |
| Lightweight user-mode threads | none built in (libraries, Go goroutines) | Fibers (CreateFiber), User-Mode Scheduling (retired) |
Seeing threads on Linux
The Threads: line of /proc/<pid>/status counts them, and each thread has its own directory in
/proc/<pid>/task/. A single-threaded tool such as grep has exactly one:
grep '^Threads' /proc/self/status
ls /proc/self/task | wc -lThreads: 1
1
The default stack size of a new Linux thread (and the main stack limit) comes from the resource limit ulimit -s,
in KiB. A child process inherits limits, and a subshell can lower its own without affecting the parent:
echo "stack limit: $(ulimit -s) KiB"
( ulimit -s 1024; echo "in the subshell: $(ulimit -s) KiB" )
echo "parent again: $(ulimit -s) KiB"stack limit: 8192 KiB
in the subshell: 1024 KiB
parent again: 8192 KiB
On a typical desktop ps -eLf or top -H lists threads (LWP = light-weight process, the thread ID):
ada@ubuntu:~$ ps -L -o pid,lwp,nlwp,comm -C firefox | head -4 # sample output — yours will differ
PID LWP NLWP COMMAND
3120 3120 112 firefox
3120 3127 112 firefox
3120 3128 112 firefoxSeeing threads on Windows
Task Manager's Details tab can add a Threads column; PowerShell exposes each thread with its state and wait reason (sample output — yours will differ):
PS C:\Users\ada> (Get-Process explorer).Threads | Select-Object -First 4 Id, ThreadState, WaitReason, PriorityLevel
Id ThreadState WaitReason PriorityLevel
-- ----------- ---------- -------------
8804 Wait UserRequest Normal
8940 Wait EventPair Normal
9012 Wait UserRequest Highest
9180 Wait Executive NormalA race condition, simulated
Why does shared memory need care? counter += 1 is really three steps: load the value into a register, add,
store it back. If the scheduler switches threads between those steps, an update is lost. Real thread timing is
not reproducible, so this Python program plays scheduler itself and runs two "threads" step by step in a fixed
interleaving:
counter = 0
def increment(name, log):
"""A generator: each yield is a point where the scheduler may switch threads."""
global counter
reg = counter # 1. load
log.append(f"{name}: load {reg}")
yield
reg = reg + 1 # 2. add (in a private register)
log.append(f"{name}: add -> {reg}")
yield
counter = reg # 3. store
log.append(f"{name}: store {reg}")
yield
def run(schedule):
global counter
counter = 0
log = []
threads = {"T1": increment("T1", log), "T2": increment("T2", log)}
for name in schedule:
next(threads[name], None)
for line in log:
print(" " + line)
print(f" final counter = {counter} (expected 2)\n")
print("Serial: T1 finishes before T2 starts")
run(["T1", "T1", "T1", "T2", "T2", "T2"])
print("Interleaved: both load before either stores")
run(["T1", "T2", "T1", "T2", "T1", "T2"])Serial: T1 finishes before T2 starts
T1: load 0
T1: add -> 1
T1: store 1
T2: load 1
T2: add -> 2
T2: store 2
final counter = 2 (expected 2)
Interleaved: both load before either stores
T1: load 0
T2: load 0
T1: add -> 1
T2: add -> 1
T1: store 1
T2: store 1
final counter = 1 (expected 2)
The second schedule loses an update. On a real machine this happens rarely and unpredictably, which is why race
conditions are among the hardest bugs to find. The cure is a lock (a mutex, a futex on Linux, an SRW lock or
critical section on Windows) or an atomic instruction (lock xadd on x86, InterlockedIncrement on Windows,
__atomic_fetch_add with GCC).
User threads, kernel threads and the M:N idea
The threads above are kernel threads: the OS knows about each one and schedules it. Some runtimes put many user-level threads on top of fewer kernel threads:
| Model | How it works | Examples |
|---|---|---|
| 1:1 | Every language thread is one kernel thread | pthreads on Linux, Win32 threads, Java platform threads |
| M:N | Many green threads multiplexed onto a pool of kernel threads | Go goroutines, Java virtual threads, Erlang processes |
| N:1 | All user threads on one kernel thread | Old "green threads", Windows fibers, Python generators/asyncio |
Learn more: CPU Scheduling · Synchronization & Deadlocks
Test yourself
What do two threads of the same process NOT share?
- Global variables
- Open file descriptors / handles
- Their stacks and register sets
- The heap
Which Linux system call creates threads under the hood of pthread_create()?
- fork
- clone
- vfork
- CreateThread
Why can counter += 1 from two threads lose an update?
- Python forbids it
- It is a load, add and store, and a thread switch can happen between them
- Threads have separate copies of global variables
- The CPU caches are never synchronized