Boss lesson · Unit 03
Why didn't threads make it faster
The GIL, processes, and picking the right tool
What you practise
- Python's GIL: threads help I/O but not CPU work
- Processes for CPU and what crossing a process costs
- Node's single thread and worker threads
- Picking the tool for a job
Try a question from this lesson
Pick one
A Python function counts primes: 4 s of pure computing. You run it 4 times on a 4-core laptop, using 4 threads. About how long does it take?
Correct answer
About 16 s
Why
Standard Python lets only one thread run Python code at a time. The four threads take turns on what amounts to one core: 4 × 4 s, the same as using no threads at all.
The ideas
Concept cards are short on purpose. In the app they appear between questions, after you have met the idea.
Concept
The GIL
Standard Python (CPython) has one Global Interpreter Lock. A thread must hold it to run Python code, so threads take turns: concurrent, never parallel.
A thread lets go of the GIL while it waits for the network, the disk or a sleep. That is why threads still speed up I/O-bound work.
computing: one thread runs at a time
T1 run wait run wait
T2 wait run wait run
waiting: the GIL is let go
T1 run wait........ run
T2 run wait... runConcept
Processes
A process has its own memory and its own interpreter, so its own GIL. Four processes can compute on four cores at the same instant.
The price: processes share nothing. Every argument and every result is packed up, copied across and unpacked.
Use them for big chunks of computing, not for tiny tasks.
10 more exercises in the app
- 4× multiple choice
- 3× type the answer
- 1× true or false
- 1× fill the blanks
- 1× match the pairs
Bitpath is an iOS app in development. Join the waitlist and you get one email when it is ready to try.