Repository navigation
Operating Systems 03 threads
Relevant source files
The following references were used as context for generating this wiki page:
- Wikipedia: Thread (computing)
- Wikipedia: Context switch
- Book: Silberschatz, Galvin and Gagne, Operating System Concepts, chapter 4
A thread is one flow of execution inside a process. A process starts with one thread; it can create more, and all of them share the process's memory and open files while each keeps its own registers and stack. Threads let one program do several things at once, for example a browser downloading a page while still responding to clicks.
Code on this page is illustrative C using POSIX threads (
pthread).
This page covers what threads share and what each owns, threads versus processes, user-level versus kernel-level threads and the threading models, thread pools, and why threads need synchronization. Locks themselves are on Synchronization.
| Office | Process with threads |
|---|---|
| One office (rooms, filing cabinets, phone line) | One process: address space, open files |
| Several workers in that office | Several threads |
| Each worker's own notepad and current task | Each thread's own registers, PC and stack |
| Everyone can open every filing cabinet | Every thread can read and write all the process's memory |
| Two workers editing the same file at once | A race condition: needs a lock |
A separate process would be a separate office: safer, but sharing papers means posting them (IPC).
flowchart TB
subgraph P["One process"]
direction TB
SH["Shared by all threads:<br/>code, globals, heap,<br/>open files, signal handlers, PID"]
subgraph T1["Thread 1"]
R1["registers, PC"]
S1["own stack"]
end
subgraph T2["Thread 2"]
R2["registers, PC"]
S2["own stack"]
end
subgraph T3["Thread 3"]
R3["registers, PC"]
S3["own stack"]
end
end
| Shared (per process) | Private (per thread) |
|---|---|
| Code (text) | Program counter |
| Global and static variables | Registers |
| Heap | Stack (local variables, call frames) |
| Open file descriptors | Thread ID |
| Current directory, user ID | Thread-local storage (thread_local) |
| Signal handlers | Signal mask, scheduling state |
Trap: a thread's stack is private by convention, not protected. Another thread holding a pointer to it can still read or overwrite it.
| Process | Thread | |
|---|---|---|
| Memory | Own address space | Shares the process's address space |
| Creation cost | Higher (new page tables, PCB) | Lower |
| Context switch | Slower: page table and TLB change | Faster: same address space |
| Communication | IPC through the kernel | Just read and write shared variables |
| A crash (bad pointer) | Kills only that process | Kills the whole process, all threads |
| Isolation | Strong | None between threads |
Typical choices: browsers use a process per tab for isolation and threads inside each; servers use a pool of threads for speed.
Sources: Wikipedia: Thread (computing)
// illustrative
#include <pthread.h>
#include <stdio.h>
void *worker(void *arg) {
int id = *(int *)arg;
printf("hello from thread %d\n", id);
return NULL;
}
int main(void) {
pthread_t t[4];
int ids[4];
for (int i = 0; i < 4; i++) {
ids[i] = i; // one slot per thread, not &i
pthread_create(&t[i], NULL, worker, &ids[i]);
}
for (int i = 0; i < 4; i++)
pthread_join(t[i], NULL); // wait for each thread
return 0;
}The output order of the four lines can differ from run to run: the scheduler decides which thread runs when.
Trap: passing &i to every thread is a classic bug; all threads share one i that keeps changing.
| User-level threads | Kernel-level threads | |
|---|---|---|
| Managed by | A library in the process | The kernel |
| Kernel knows about them? | No: sees one thread | Yes: schedules each one |
| Switch cost | Very cheap (no system call) | Needs the kernel |
| One thread blocks on I/O | The whole process blocks | Only that thread blocks |
| Use multiple cores | No | Yes |
flowchart LR
subgraph M1["Many-to-one"]
u1["U"] --> k1["K"]
u2["U"] --> k1
u3["U"] --> k1
end
subgraph OO["One-to-one"]
a1["U"] --> b1["K"]
a2["U"] --> b2["K"]
a3["U"] --> b3["K"]
end
subgraph MM["Many-to-many"]
c1["U"] --> d1["K"]
c2["U"] --> d1
c3["U"] --> d2["K"]
c4["U"] --> d2
end
| Model | Description | Example |
|---|---|---|
| Many-to-one | All user threads on one kernel thread | Old "green threads" |
| One-to-one | Each user thread is a kernel thread | Linux pthreads, Windows threads |
| Many-to-many | M user threads multiplexed on N kernel threads | Go goroutines, Erlang processes (runtime schedulers) |
Creating a thread for each request wastes time and can create too many threads. A thread pool creates a fixed set of worker threads once; work items go into a queue and idle workers take them.
flowchart LR
R1["Request"] --> Q["Work queue"]
R2["Request"] --> Q
R3["Request"] --> Q
Q --> W1["Worker 1"]
Q --> W2["Worker 2"]
Q --> W3["Worker 3"]
The queue itself is a producer-consumer buffer, see Synchronization.
| Meaning | Needs multiple cores? | |
|---|---|---|
| Concurrency | Several tasks make progress over the same period, possibly by taking turns | No |
| Parallelism | Several tasks run at the same instant | Yes |
flowchart TB
subgraph C["Concurrent on 1 core"]
c["A A B B A B A A"]
end
subgraph P["Parallel on 2 cores"]
p1["core 0: A A A A"]
p2["core 1: B B B B"]
end
Because threads share memory, two threads updating the same variable can interfere:
// illustrative: two threads each run this 1,000,000 times
counter++; // load, add 1, store: three steps, not oneThe final value is often less than 2,000,000, because both threads can load the same old value before either stores. Fixing this is the subject of Synchronization.
- Threads share the heap and globals but not the stack or registers.
- A segfault in one thread kills the whole process.
- Output order between threads is not guaranteed without synchronization.
- User-level threads alone cannot use more than one core.
- Process vs thread? A process has its own address space; threads within a process share it, each with its own registers and stack. Threads are cheaper to create and switch but give no isolation.
- What do threads in one process share? Code, globals, heap, open files, signal handlers. Not stacks, registers or program counters.
- Why is a thread switch cheaper than a process switch? The page table stays the same, so there is no address-space switch and the TLB and caches stay warm.
- User vs kernel threads? User threads are managed by a library and invisible to the kernel; cheap but one blocking call blocks all, and no multicore. Kernel threads are scheduled individually by the kernel.
- Concurrency vs parallelism? Concurrency is dealing with many things at once (interleaving); parallelism is doing many things at once (multiple cores).
- Why use a thread pool? It avoids the cost of creating threads per task and bounds the number of threads.
- A thread is an execution flow inside a process: own registers, PC and stack; shared memory and files.
- Threads are cheaper than processes but give no isolation; shared data needs synchronization.
- Linux uses one-to-one kernel threads; runtimes like Go multiplex many user threads on few kernel threads.
- Computer Architecture Overview
- Fundamentals: CPU, Memory and Instructions
- Pipelining
- Branches and Remedies
- Instruction-Level Parallelism
- Memory and Ordering
- Caches and Coherence
- Multicore
- Multithreading in Hardware
- SIMD and GPUs
- Glossary and Summary
- Hexagon Overview and Processor Properties
- ISA Fundamentals: Packets, Slots and Threads
- Registers
- Instruction Encoding and Mnemonics
- Data, Memory and Control Instructions
- Floating Point, HVX and Alignment
- Caches, MMU and Glossary
- Operating Systems Overview
- Processes
- Threads
- CPU Scheduling
- Synchronization
- Deadlock
- Memory Management
- Virtual Memory
- Files, Storage and I/O
- Kernel and System Calls
- Interview Q&A and Glossary
- C++ for LLVM Development: Overview
- C++ Basics
- Classes and RAII
- Ownership and Move Semantics
- Templates and Lambdas
- LLVM Data Structures (ADT)
- LLVM-Style RTTI: isa, cast, dyn_cast
- Errors, Output and Assertions
- Iterators and Ranges
- Building, Debugging and Exercises
- LLVM IR Overview
- Structure: Modules, Functions, Blocks and Values
- Type System
- Arithmetic, Bitwise and Cast Instructions
- Compare and Select
- Memory: alloca, load, store and getelementptr
- Control Flow: br, switch, ret and call
- SSA and Phi
- Control Flow Graph and Loops
- Dominance, Dominator Tree and Dominance Frontier
- Data-flow Analysis
- Writing an IR Pass
- Common Passes
- Exercises, Tooling and Glossary
- SelectionDAG Overview
- Pipeline, Phases and Traversal Orders
- Core Data Structures
- DAG Construction
- DAG Combiner
- Legalization
- Type Legalization
- Operation and Vector Legalization
- Instruction Selection
- TableGen Pattern Language
- Matcher Interpreter and Folding
- AArch64 Instruction Selection
- Scheduling and MIR Emission
- PHI Node Resolution
- AArch64 Walkthroughs
- Arithmetic and Data Movement
- Memory Instructions
- Control Flow and Calls
- End-to-End Example
- Tooling, Debugging and Extending
- Selector Comparison and Glossary
- Assignments: Build the Toy Backend
- Stage 1: Build Setup
- Stage 2: Target Registration
- Stage 3: TableGen Skeleton
- Stage 4: MC Layer for Assembly Output
- Stage 5: TargetMachine and Subtarget
- Stage 6: TargetLowering, Arguments and Returns
- Stage 7: Instruction Selection and the First Function
- Stage 8: Registers, Copies and Spills
- Stage 9: Frame Lowering
- Stage 10: Memory, Globals and Control Flow
- Stage 11: Calls
- Stage 12: Scheduling Model
- Stage 13: Object Files
- Stage 14: Capstone, a Complete Toy Backend
- Target Bring-up Overview
- Directory Layout, CMake and Registration
- The Target .td File
- TargetMachine and Subtarget
- TargetLowering Setup
- Calling Conventions
- Instructions and Instruction Selection
- Registers and Allocation Hooks
- Frame Lowering
- AsmPrinter and the MC Layer
- Scheduling
- A Minimal Toy Target
- Bring-up Checklist and AArch64 File Map
- Tooling and Glossary
- Calling Conventions Overview
- The CallingConv.td Language
- CCState and CCValAssign
- LowerFormalArguments
- LowerCall
- LowerReturn and CanLowerReturn
- Varargs, byval, sret and swifterror
- Tail Calls and Sibling Calls
- Custom Backend Guide and Checklist
- AArch64 Walkthroughs
- Tooling and Glossary
- Frame Lowering Overview
- MachineFrameInfo
- TargetFrameLowering Hooks
- The PEI Pass
- Callee-Saved Registers and Stack Layout
- Frame Index Elimination and the Register Scavenger
- Shrink Wrapping
- CFI and Unwind Information
- Custom Backend Guide and Checklist
- AArch64 Walkthroughs
- Tooling and Glossary
- MC Layer Overview
- Core Data Structures
- Streamers
- Assembler and Layout
- Fixups and Relocations
- Writing an MC Layer for a Custom Backend
- MCAsmInfo and the Instruction Printer
- Code Emitter
- AsmBackend and Object Writer
- Assembly Parser and Disassembler
- Bring-up Checklist and Common Failures
- Tooling and Glossary
- Register Allocation Overview
- The Register Allocation Pipeline
- Registers, Virtual Registers and Register Classes
- Liveness: Slot Indexes and Live Intervals
- Preparing Code for Allocation
- PHI Elimination and Two-Address Lowering
- Register Coalescer
- Allocation Framework
- The Register Allocators
- Fast Register Allocator
- Basic Register Allocator
- Greedy Register Allocator
- PBQP Register Allocator
- Spilling and Splitting
- Spill Weights and Copy Hints
- The Inline Spiller
- Live Range Splitting
- Rewriting and Post-RA Passes
- Writing Register Allocation Support for a Custom Backend
- Register Definitions in TableGen
- TargetRegisterInfo Hooks
- TargetInstrInfo Hooks
- Pass Pipeline Hooks
- Bring-up Checklist and Common Failures
- AArch64 Walkthroughs
- Tooling and Debugging
- Glossary and Where Do I Look