Threads and Shared Memory
Threads inside one process share an address space and everything in it, which makes them cheap to switch between and dangerous to reason about. The gain is a program that keeps working while one part waits; the cost is that any two threads can touch the same variable.
What a learner can do afterwards
- Say what threads in one process share and what each keeps to itself
- Explain why creating a thread is cheaper than creating a process
- Identify a variable in a small program that two threads could reach at once
1 · Read
An address space is the set of addresses a program uses to reach its instructions and data. Every process gets its own, kept private by address translation, so two programs cannot read each other's memory. Threads bend this rule on purpose: all threads inside one process live in the same address space, reading and writing the same variables with no barrier between them.
Picture a counter called total that two threads both raise by one. Either thread can reach total at any moment, since it sits in their shared space. If both read it at the same time and both write back, one raise gets lost and the threads have stepped on each other. Each thread keeps its own CPU state, its program counter, stack pointer and registers, but the variables are shared.
That sharing is why creating a thread is cheaper than creating a process. A new process needs a fresh address space with fresh translation, while a new thread reuses the one already there. Switching between threads of one process is cheap for the same reason: the shared space stays put, so there is far less to swap.
The gain is a program that keeps working while one part waits, since another thread can run meanwhile. The cost is that any two threads can touch the same variable, so guard shared data and let only one thread change it at a time. Keep the sharing for speed, and remove the stepping for safety.
Threads share one address space, which makes them cheap and lets them collide, so guard the data they share.
2 · Watch
Take it off screen
Where it sits
Learn first
This opens up
8 questions wait behind this lesson, each with its answer explained. Every answer feeds the sky: stars light as they are learned, and dim when it is time to come back.