Sub topic 13
Why some native libraries run in parallel threads
This chapter assumes you know that CPython threads share one Global Interpreter Lock (GIL), and that pure-Python CPU-bound threads do not run in parallel. It also assumes you can use ThreadPoolExecutor. The earlier chapters on the GIL and its effect on threads cover both. Here you will see why that limit does not apply to some code, how to tell which code it applies to, and what to watch for.
The GIL protects the interpreter, not your data
The GIL exists to keep the interpreter's internal state consistent. Reference counts, the object allocator, and the bytecode evaluation loop all assume only one thread touches them at a time. The lock is needed only while code is working with Python objects.
Native code, such as C, C++, Rust, or Fortran, often does work that never touches Python objects. Examples are hashing a block of memory, compressing a buffer, multiplying two matrices, or waiting on a socket. While that work runs, nothing in the interpreter's state is at risk. The native function can therefore release the GIL, do its work, and take the GIL back before it returns to Python.
While the GIL is released, another thread can run Python bytecode. Several threads can also sit in native code at once. Each runs on its own CPU core, so the work runs in parallel.
What the release looks like in C
You do not need to write extensions to use this chapter, but the mechanism is short. In the C API, the macros Py_BEGIN_ALLOW_THREADS and Py_END_ALLOW_THREADS wrap the section that runs without the GIL. The function below is a sketch of an extension function, with the module boilerplate omitted.
#define PY_SSIZE_T_CLEAN
#include <Python.h>
static PyObject *checksum(PyObject *self, PyObject *args)
{
Py_buffer view;
if (!PyArg_ParseTuple(args, "y*", &view)) {
return NULL;
}
unsigned long total = 0;
const unsigned char *p = view.buf;
Py_ssize_t n = view.len;
Py_BEGIN_ALLOW_THREADS
for (Py_ssize_t i = 0; i < n; i++) {
total += p[i];
}
Py_END_ALLOW_THREADS
PyBuffer_Release(&view);
return PyLong_FromUnsignedLong(total);
}Everything between the two macros runs without the GIL. The code inside must not call any Python API, because those calls assume the GIL is held. The code copies what it needs, here a pointer and a length, into plain C variables before releasing the lock.
Other tools do the same thing for you:
- Cython offers
with nogil:blocks andnogilfunctions. ctypesreleases the GIL while it calls a function in aCDLLlibrary.- pybind11 provides
py::gil_scoped_release. - PyO3 for Rust provides
Python::allow_threads, calleddetachin newer versions.
Measuring the difference
You can see the effect by timing the same job in one thread and in four threads. This program compares a pure-Python loop with hashlib.sha256 on a large buffer. CPython's hashlib releases the GIL when the input is larger than roughly 2 KB.
import hashlib
import time
from concurrent.futures import ThreadPoolExecutor
def pure_python(buf):
total = 0
for byte in buf[:3_000_000]:
total += byte
return total
def native(buf):
return hashlib.sha256(buf).hexdigest()
def timed(fn, jobs, threads):
start = time.perf_counter()
if threads == 1:
for job in jobs:
fn(job)
else:
with ThreadPoolExecutor(max_workers=threads) as pool:
list(pool.map(fn, jobs))
return time.perf_counter() - start
if __name__ == "__main__":
buf = bytes(100_000_000) # 100 MB of zeros, shared by all jobs
jobs = [buf] * 4
for name, fn in [("pure Python", pure_python), ("sha256", native)]:
one = timed(fn, jobs, 1)
four = timed(fn, jobs, 4)
print(f"{name:12} 1 thread {one:.2f}s 4 threads {four:.2f}s "
f"speedup {one / four:.1f}x")On a standard GIL build with at least four free cores, you should see a speedup near 1x for the pure-Python loop. For sha256 the speedup should approach the core count. The exact numbers depend on your hardware, on the load on your machine, and on whether the hash implementation uses hardware acceleration.
All four jobs share one bytes object. Threads share memory, so no copy is made. A process pool would pickle and send 100 MB to each worker first. This is a second advantage of threads when the native code releases the GIL.
Which operations release the GIL
Releasing the GIL is a choice each library makes for each function. You cannot assume it from the language the library is written in. The table gives common cases in CPython. Check the documentation or measure to be sure for your version.
| Operation | Releases the GIL? | Notes |
|---|---|---|
| `time.sleep`, socket reads and writes, file reads and writes | Yes | The reason threads help with I/O-bound work |
| `hashlib` on inputs over about 2 KB | Yes | Small inputs keep the lock because the release costs more than the work |
| `zlib`, `bz2`, `lzma` compress and decompress | Yes | Applies to large buffers |
| `sqlite3` query execution | Yes | Each thread should use its own connection |
| NumPy large-array arithmetic, reductions, and BLAS-backed `dot` | Mostly yes | Small arrays and some operations (object arrays, fancy indexing) hold the lock |
| `ctypes.CDLL` function calls | Yes | `ctypes.PyDLL` does not release it |
| Pure-Python loops and functions | No | Bytecode needs the GIL |
| C code that calls back into Python | Reacquires | A callback needs the GIL for its duration |
Common pitfalls
Too little native work per call
Releasing and reacquiring the GIL costs time, and the reacquire step can make a thread wait. If each native call finishes in microseconds, the thread spends more time handing the lock back and forth than computing. This is why hashlib skips the release on small inputs. Give each task a large chunk of work, such as a whole array or file, and avoid calling a native function a million times on tiny pieces.
Callbacks and mixed workloads
A task that alternates between native code and Python code runs in parallel only during the native part. If 50% of a task's time is spent in Python bytecode, Amdahl's law limits four threads to a speedup of about 1.6x, however fast the native part is. Profile a single task first to find out how its time splits.
Oversubscription
Some native libraries already use several threads inside one call. NumPy with OpenBLAS or MKL is the usual example. If you run eight Python threads that each call a matrix multiply using eight BLAS threads, you get 64 busy threads on eight cores. The result is often slower than either layer alone. Either limit the library's own threads (for example with the OMP_NUM_THREADS or OPENBLAS_NUM_THREADS environment variables, set before the library loads) or use fewer Python threads.
Shared buffers and mutation
A native function that works without the GIL reads memory while other threads run Python code. If the buffer is a bytearray or a NumPy array and another thread changes it, the native code can see half-updated data. Immutable objects like bytes are safe to share. For mutable data, give each thread its own slice, as in the next example, or protect the buffer with a lock.
Native code can still be thread-unsafe
Releasing the GIL says nothing about whether the library is thread-safe. A C library that keeps global state may corrupt it when two threads call it at once. Release of the GIL is the library author's decision, and the author must also make the code safe to call concurrently. Read the library's documentation on thread safety.
Splitting one job across threads
When a library releases the GIL, you can speed up one large job by splitting the data. This example sums the squares of a large NumPy array in four chunks. NumPy slices are views, so no data is copied.
import time
from concurrent.futures import ThreadPoolExecutor
import numpy as np
def chunk_sum(chunk):
return float(np.sum(chunk * chunk))
if __name__ == "__main__":
data = np.random.default_rng(0).random(80_000_000)
chunks = np.array_split(data, 4)
start = time.perf_counter()
serial = chunk_sum(data)
t_serial = time.perf_counter() - start
start = time.perf_counter()
with ThreadPoolExecutor(max_workers=4) as pool:
parallel = sum(pool.map(chunk_sum, chunks))
t_threads = time.perf_counter() - start
print(f"serial {t_serial:.2f}s threads {t_threads:.2f}s")
print(np.isclose(serial, parallel))The results are the same up to floating-point rounding, which is why the program compares them with np.isclose instead of ==. This job is partly memory-bound, so the speedup is often smaller than the core count. Memory bandwidth, not the GIL, becomes the limit.
The limit of this approach
If a native library releases the GIL for the heavy part of your work, threads are usually the simplest model. They avoid process startup, pickling, and duplicated memory. If you are unsure, measure with both a thread pool and a process pool, as in the earlier chapters. Also check the status of the free-threaded build, covered in a later chapter. In a free-threaded interpreter, C extensions must declare that they are safe without the GIL, and importing one that does not declare it can turn the GIL back on.
Exercise
A colleague wraps a C compression library with a Python function that, for each 4 KB block of a file, calls the C function, which releases the GIL, and then appends the result to a list in Python. They run it on four threads and see almost no speedup. Give two likely reasons and one change that might help.
Show answer
First, each native call is tiny, so the cost of releasing and reacquiring the GIL, plus waiting to reacquire it while other threads run bytecode, is comparable to the compression work. Second, the Python code around each call (the loop, the list append) holds the GIL, so the threads spend much of their time waiting for one another. Passing much larger blocks per call (for example several megabytes) or compressing whole chunks of the file per task gives each thread more native work per GIL handoff and should improve the speedup. Measuring one task to see how its time splits between native and Python code confirms the cause.
Exercise
Why does the 100 MB hashing example in this chapter avoid copying data to the workers, and what would change if you used ProcessPoolExecutor instead?
Show answer
Threads share one address space, so all four tasks receive a reference to the same bytes object and nothing is copied. ProcessPoolExecutor runs workers in separate processes, so each task's argument is pickled and sent to a worker, which copies the 100 MB for every task. The copying adds time and memory, and it can outweigh the benefit of parallel hashing.