Sub topic 2
What the GIL Is and What It Protects
Assume you know how to write Python functions, use with statements, and run scripts. This chapter focuses on CPython, the most common Python implementation.
The GIL and shared state
The Global Interpreter Lock (GIL) is a lock in standard CPython. It allows only one thread at a time to execute Python bytecode in an interpreter. Python bytecode is the low-level instruction form produced from Python source code.
The GIL protects CPython's internal memory-management state. It helps keep operations on objects, reference counts, and interpreter data consistent. It does not make your program's data automatically safe.
For example, counter += 1 involves reading, adding, and writing. Another thread can run between those steps. Use a lock when multiple threads update shared mutable state.
import threading
counter = 0
lock = threading.Lock()
def add_many():
global counter
for _ in range(100_000):
with lock:
counter += 1
threads = [threading.Thread(target=add_many) for _ in range(4)]
for thread in threads:
thread.start()
for thread in threads:
thread.join()
print(counter)I/O-bound and CPU-bound threads
I/O-bound work spends time waiting for a network, file, or timer. While a thread waits, CPython can let another thread run. Threads often improve throughput for this kind of work.
CPU-bound work spends most of its time executing Python instructions. On a GIL-enabled build, Python threads take turns, so they usually do not make pure-Python calculations faster on multiple cores.
Processes and executor pools
A process has its own interpreter and memory. Separate processes can execute Python code on different CPU cores without sharing one GIL. The cost is higher startup time and communication overhead. Values sent between processes are usually pickled, which serializes them.
ProcessPoolExecutor manages worker processes. ThreadPoolExecutor offers the same convenient interface for threads.
from concurrent.futures import ThreadPoolExecutor, ProcessPoolExecutor
def square(n):
return n * n
if __name__ == "__main__":
with ThreadPoolExecutor(max_workers=4) as pool:
print(list(pool.map(square, range(4))))
with ProcessPoolExecutor(max_workers=4) as pool:
print(list(pool.map(square, range(4))))Use threads for waiting-heavy tasks and processes for independent, CPU-heavy Python tasks. Measure with realistic inputs, because process startup and pickling can outweigh the speedup.
Exercise
Why does a process pool usually help pure-Python CPU work more than a thread pool?
Show answer
Processes use separate interpreters and GILs, allowing Python code to run on multiple CPU cores. Threads in one GIL-enabled interpreter take turns executing Python bytecode.