liveBook · Manning

Global interpreter lock

As explained in Refactoring to Rust

The Python Global Interpreter Lock is a synchronization mechanism in CPython that restricts execution of Python bytecode to one thread at a time within a process.

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

How Refactoring to Rust covers it

How deep it goes
Explains the lock’s safety and threading role, then demonstrates acquiring and releasing it through PyO3.
Examples
Uses a hall-pass analogy, a Python-versus-Rust JSON benchmark, and a Mandelbrot computation submitted to a thread pool.
What you can do after
Apply it via PyO3 to acquire the GIL for Python operations and release it around a Rust computation.
How it connects
Connects the GIL to thread safety, mutexes, thread pools, and Python extension modules.

Also explained in

Compare how 5 books explain global interpreter lock →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Refactoring to Rust. The section links point to the parts of the book it draws on.