Quiz
Warm-up from lessons 3-1 and 4-1: two PROCESSES never see each other's variables. Which memory does each process have privately?
A second line of execution in the same process
Sometimes you want two things happening at once inside one program: download a file while the UI stays responsive, or handle many web requests together. You could launch a second process, but processes cannot share variables.
A thread is a second line of execution inside the same process. Key facts:
- Each thread gets its own stack (its own chain of function calls).
- All threads in a process share the same heap: the same lists, dicts, and objects.
- The OS schedules threads just like processes, pausing and resuming them whenever it wants.
Shared heap is the superpower and the danger. Two threads can build one result together, and two threads can silently corrupt the same data.
Code exercise · python
Run this. Two threads "brew" at the same time by sleeping 0.2s and 0.4s. Total time is about 0.4s, not 0.6s, proving they overlapped. They share the results list because the heap is shared.
Code exercise · python
Your turn. Start three threads running fetch (one per name in the list), then join them all so the main thread waits for every worker. Print how many tasks finished and the sorted results. The shared results list works because all threads share the heap.
Quiz
When would you pick threads over separate processes?