Lesson 17: Threads and the GIL
So far every program in this course has done one thing at a time, in order. Real programs often need to do several things at once: download three files while keeping the interface responsive, or handle many users at the same time. Python's first tool for that is the thread: a separate flow of execution inside the same process, sharing the same memory. The threading module lets you start a thread with a target function, and the example below downloads — or rather, pretends to download — three files at the same time, finishing in roughly the time of the slowest one instead of the sum of all three.
Threads share memory, and that sharing is both their strength and their danger. If two threads change the same variable at the same time, the result depends on the exact order they run in — a bug called a race condition, which may appear once in a thousand runs and vanish when you try to reproduce it. The standard defence is a Lock: a thread must acquire the lock before touching shared data, and release it afterwards, so only one thread is inside the critical section at a time. The example uses a lock to protect a shared counter.
import threading
import time
counter = 0
lock = threading.Lock()
def work(n):
global counter
time.sleep(0.1) # pretend to do something slow
with lock:
counter += n
threads = [threading.Thread(target=work, args=(1,)) for _ in range(5)]
for t in threads:
t.start()
for t in threads:
t.join()
print(counter) # 5 — every increment protected by the lock
The GIL: what threads can and cannot speed up
Python threads have a famous limitation: the Global Interpreter Lock, or GIL. The GIL is a lock inside the interpreter that allows only one thread to run Python code at a time. That sounds like it defeats the purpose of threads, and for CPU-heavy work it does: ten threads crunching numbers will not finish faster than one. But for I/O-bound work — waiting for a download, a file, or a database — threads shine, because a thread waiting for data releases the GIL, and another thread runs in the meantime. The rule of thumb is simple: threads for waiting, processes for computing. The next lesson covers the computing side.
A practical consequence is that you should reach for threads when your program spends its time waiting, and avoid shared mutable state wherever you can. Give each thread its own data where possible, use a queue to pass work between threads instead of sharing variables, and keep critical sections — the code inside a lock — as short as you can. Threads are a powerful tool, but they are also the easiest way to write a bug that only appears on a busy day. Respect them, test under load, and prefer simpler designs when they will do.
Going further
Threads can be marked as daemon threads, which means the program will not wait for them when the main thread finishes — they are abandoned instead. That is useful for background jobs like watching a folder or sending a heartbeat, where you do not want a forgotten thread to keep the program alive forever. The default is the opposite: a normal thread keeps the program running until it finishes, which is why the example calls join() explicitly. Choose daemon threads only for work that is safe to abandon halfway.
For many threading jobs, the concurrent.futures module is a cleaner interface than managing threads by hand. A ThreadPoolExecutor keeps a pool of worker threads, you submit functions to it, and it hands you back future objects representing the results. Downloading ten files becomes a few lines: submit ten download functions, then collect the results as they complete. The executor handles starting, joining and error reporting for you, and the same interface works for processes — swap ThreadPoolExecutor for ProcessPoolExecutor and the same code runs in parallel across cores.
Race conditions are hard to believe in until you have seen one, so try to cause one on purpose. Write a program where ten threads each add one to a shared counter a thousand times, without a lock — but with a twist: read the counter into a local variable, pause for a thousandth of a second, and then write the incremented value back. That pause makes it likely that two threads read the same value before either writes, so one increment is lost, and the final total comes out short of ten thousand. Without the pause the race may never show up, because each increment is so fast that threads rarely interrupt each other mid-step — which is itself the lesson. A race condition is a bug that depends on timing, so it appears in production and vanishes in testing, and the only reliable defence is to protect the shared data every time.
Key Terms
- Thread
- A separate flow of execution inside one process, sharing the process's memory.
- threading
- The standard-library module for creating and managing threads.
- Race condition
- A bug where the result depends on the unpredictable order in which threads run.
- Lock
- An object that only one thread can hold at a time, protecting shared data from simultaneous changes.
- GIL (Global Interpreter Lock)
- A lock in the Python interpreter that allows only one thread to execute Python code at a time.
- I/O-bound
- Work that spends most of its time waiting for input or output, such as downloads — where threads help.
- CPU-bound
- Work that spends most of its time computing — where threads do not help because of the GIL.
- join()
- Waits for a thread to finish before the program continues.
Discussion Questions
- Why do threads help a program that downloads files, but not a program that crunches numbers? What is the GIL doing in each case?
- A race condition may appear once in a thousand runs. Why does that make it harder to fix than a bug that happens every time?
- When would you use a queue to pass work between threads instead of a shared variable protected by a lock?
Practice Questions
- What does
t.join()do? - What would happen to the counter if the lock were removed?
- Is a program that sorts a million numbers a good fit for threads? Why not?
- Give an example of I/O-bound work where threads help.
- What is a critical section?
Show answers
- It waits until thread t has finished. The main program only prints the counter after all five threads have joined.
- It could end up below 5. Two threads might read the same value, both add one, and both write back the same result — a lost update.
- No — sorting is CPU-bound. The GIL allows only one thread to run Python code at a time, so threads add overhead without speed.
- Downloading several files, or handling many network requests at once. While one thread waits for data, the GIL is released and another thread can run.
- The code that touches shared data, protected by a lock. Only one thread may be inside it at a time; keep it as short as possible.