`PyThreadState`'s Role: Preserving Python Context

The `nogil` mechanism critically relies on the `PyThreadState` structure, which holds the execution context for a Python thread, including its interpreter state, current frame, and exception status. When `PyEval_SaveThread()` is called, this thread state is detached and saved, allowing the C code to run. `PyEval_RestoreThread()` then uses the saved `PyThreadState` to restore the Python context, ensuring the interpreter's integrity and seamless continuation.

Sources

Open the full topic