Multithreading Basics
intermediateMultithreading lets a program run several sequences of instructions at the same time. Each sequence is called a thread, and the program can make progress on multiple tasks concurrently.
Process vs. Thread
| Process | Thread | |
|---|---|---|
| Meaning | A running program with its own memory | A single execution path inside a process |
| Memory | Isolated from other processes | Shares the process memory (heap, globals) |
| Creation cost | Heavy (new address space) | Light (shares existing resources) |
| Communication | Inter-process communication (IPC) | Direct access to shared data |
Because threads share memory, communication is fast — but sharing also means two threads can touch the same data at the same time.
Why Use Multithreading?
- Responsiveness: keep a UI responsive while work happens in the background
- Performance: use multiple CPU cores to finish compute-heavy work sooner
- Throughput: overlap I/O waits (disk, network) with other work
- Simplicity: model naturally concurrent tasks (e.g. a download per file)
Concurrency vs. Parallelism
Concurrency means multiple tasks make progress by interleaving — even on a single core. Parallelism means tasks literally run at the same instant on different cores. Multithreading can provide either, depending on the hardware.
The Main Thread
Every C++ program starts with one thread — the one that runs main(). Additional threads are created explicitly and run a function of your choosing.
More threads is not always faster. Threads add scheduling and synchronization overhead, and shared data introduces the risk of race conditions. Measure before parallelizing.
Key takeaway: A thread is a lightweight execution path that shares its process's memory. Multithreading improves responsiveness and can use multiple cores, but shared data must be synchronized.
Try it: Name two tasks in a program you use that could run concurrently, and say whether each benefits more from responsiveness or from throughput.