The global interpreter lock (GIL) is a CPython synchronization mechanism that allows only one thread at a time to execute Python bytecode within a process. It protects interpreter resources, including core data structures that are not thread-safe. section 8.5 section 6.5
Think of the GIL as a hall pass: a thread needs the pass to use protected interpreter resources, and another thread must wait until it is available. This limits parallel execution of Python code, so adding threads alone may not speed up CPU-bound work. section 8.5 section 8.6
When Rust code needs to work with Python objects through PyO3, it must hold the GIL where required. Python::with_gil acquires it and passes a handle into a closure; that handle is used to create Python objects and run Python code. section 6.5
use criterion::Bencher;
use pyo3::prelude::*;
use pyo3::types::PyDict;
fn bench_py(b: &mut Bencher, code: &str, input: &str) {
Python::with_gil(|py| {
let locals = PyDict::new(py);
locals.set_item("json", py.import("json").unwrap()).unwrap();
locals
.set_item("rust_json", py.import("rust_json").unwrap())
.unwrap();
locals.set_item("INPUT", input).unwrap();
b.iter(|| black_box(py.run(code, None, Some(&locals)).unwrap()));
});
}
This benchmark helper acquires the GIL, creates a Python locals dictionary, imports modules, and runs the supplied Python code. section 6.5
For work that does not need Python objects, a Rust extension can release the GIL while it runs, allowing other Python threads to proceed. Releasing the lock is a targeted change; it does not remove the need to hold it when accessing Python resources. section 8.6 section 6.5
Listing 8.11 lib.rs: Adding a thread-safe function
#[pyfunction]
fn mandelbrot_fast(
py: Python<'_>,
size: u32,
path: &str,
range_x0: f64,
range_y0: f64,
range_x1: f64,
range_y1: f64,
) {
py.allow_threads(|| mandelbrot_func(size, path, range_x0, range_y0,
range_x1, range_y1)) #1
}
#[pymodule]
fn mandelbrot(_py: Python, m: &PyModule) -> PyResult<()> {
...
m.add_function(wrap_pyfunction!(mandelbrot_fast, m)?)?;
Ok(())
}
The Mandelbrot wrapper uses py.allow_threads to run the Rust computation with the GIL released. section 8.6




