Sub topic 13
Why some native libraries run in parallel threads
This chapter assumes you know that the GIL lets only one thread run Python bytecode at a time. It also assumes you have used ThreadPoolExecutor. Here you will see why CPU-heavy threads can still run in parallel when the work happens inside native code.
The GIL protects the interpreter, not your C code
The GIL guards CPython's internal state, such as reference counts and object structures. Native code that doesn't touch Python objects doesn't need that protection. A C extension can therefore release the GIL, do its heavy work on raw memory, and take the GIL back before returning to Python.
While one thread sits in the native step, another thread can hold the GIL. Several threads can also be in native steps at once, on different cores.
Who releases the GIL
Many parts of the standard library and the scientific ecosystem release the GIL around expensive operations:
| Component | What runs without the GIL |
|---|---|
| `time.sleep`, sockets, file reads | Waiting on the operating system |
| `hashlib` | Hashing large buffers |
| `zlib`, `bz2`, `lzma` | Compression and decompression |
| NumPy | Many large array operations |
| Image and database drivers | Decoding, encoding, query execution |
The standard library does this for hashing and compression only on large inputs. hashlib releases the GIL only for data above a small size threshold, because releasing and reacquiring has a cost.
Measuring it
This example hashes the same 100 MB buffer four times, first in a loop, then in four threads. The hashing is CPU work, yet the threads can overlap.
import hashlib
import time
from concurrent.futures import ThreadPoolExecutor
data = b"x" * 100_000_000
def digest(buf):
return hashlib.sha256(buf).hexdigest()
start = time.perf_counter()
for _ in range(4):
digest(data)
sequential = time.perf_counter() - start
start = time.perf_counter()
with ThreadPoolExecutor(max_workers=4) as pool:
list(pool.map(digest, [data] * 4))
threaded = time.perf_counter() - start
print(f"sequential: {sequential:.2f}s")
print(f"threaded: {threaded:.2f}s")On a multi-core machine the threaded run is usually clearly faster. Compare this with the pure-Python count_down example from the earlier chapter, where threads gave no speedup. The only difference is where the loop runs: in bytecode, or inside C.
Common errors
- Assuming a library releases the GIL. Many functions do not. Check the library's documentation, or time a threaded run against a sequential one.
- Expecting speedup from small calls. A call that finishes in microseconds spends more time on GIL handoff and Python glue than on native work. Threads help when each call does a large chunk of work.
- Forgetting the Python parts. A pipeline that alternates between native calls and Python loops is limited by the Python portions. Amdahl's law applies: the serial part sets the ceiling.
- Sharing mutable data unsafely. Releasing the GIL does not make your own shared state safe. Locks from the earlier chapter still apply to anything your Python code modifies.
Decision criteria
Use threads when the heavy work is inside a library you know releases the GIL, because threads share memory and avoid pickling. Use processes when the heavy work is pure Python, or when you cannot confirm that the library releases the GIL. A quick benchmark with both executors settles the question.
Exercise
A colleague says "threads never speed up CPU-bound code in CPython." Give one counterexample from this chapter, and explain why it works.
Show answer
Hashing a large buffer with hashlib.sha256 in several threads can run in parallel on multiple cores. hashlib releases the GIL while it hashes large data, so the work happens in C without holding the interpreter lock. The statement is true for pure-Python CPU-bound loops, but not for native code that releases the GIL.
Exercise
Why might four threads calling a native function on tiny inputs be slower than a plain loop?
Show answer
Each call does very little native work, so the overhead of releasing and reacquiring the GIL, plus thread scheduling, outweighs any parallel gain. Threads pay off only when each call does a large chunk of work without the GIL.