core-adapters 0.1.2
Third-party adapters for snicholls-core: nanobind helpers, nlohmann/json hooks, the snicholls_core Python package
Loading...
Searching...
No Matches

The GIL: release it around C++ work, take it back to call Python, and a Python callable safe from any thread. More...

#include <nanobind/nanobind.h>
#include <functional>
#include <type_traits>
#include <utility>

Go to the source code of this file.

Classes

class  snicholls::python::python_function< R(A...)>
 python_function for R(A...): takes the GIL, calls, converts the result to R. More...
 

Typedefs

using snicholls::python::release_gil = ::nanobind::call_guard<::nanobind::gil_scoped_release >
 nanobind's call guard that releases the GIL for the duration of a bound call.
 

Functions

template<class F >
decltype(auto) snicholls::python::without_gil (F &&f)
 Runs f() with the GIL released and returns its result.
 
template<class F >
decltype(auto) snicholls::python::with_gil (F &&f)
 Runs f() holding the GIL (taking it if this thread does not hold it) and returns its result.
 

Detailed Description

The GIL: release it around C++ work, take it back to call Python, and a Python callable safe from any thread.

Overview
A binding that runs C++ for more than a few microseconds should release the global interpreter lock, so other Python threads run meanwhile. Three ways, from the most declarative:
  • snicholls::python::release_gil - nanobind's call guard, as a name: .def("f", &f, release_gil()) releases the GIL for the whole call, after the arguments are converted and before the result is converted back. Use it when every argument converts to a C++ value (numbers, std::span of a NumPy array, strings); never when the function touches a Python object.
  • snicholls::python::without_gil(f) - inside a binding body: convert what needs the GIL first, then run f with the GIL released and return its result.
  • snicholls::python::with_gil(f) - the reverse, from C++ code running without the GIL (a worker thread, or inside without_gil), to call into Python.

snicholls::python::python_function<R(A...)> wraps a Python callable as a C++ callable that takes the GIL for each call (and for its own copy and destruction), so it can be handed to C++ that may run on any thread. Each call then pays for the lock: for a cooperative game evaluated 2^20 times, tabulate in Python once and pass the table instead (see snicholls_core.game).

// 1. The whole call without the GIL: arguments and result are C++ values
m.def("integrate", &integrate, "steps"_a, snicholls::python::release_gil());
// 2. Convert first, then release for the C++ part only
m.def("integrate_twice", [](std::size_t steps) {
const double once = snicholls::python::without_gil([&] { return integrate(steps); });
return 2 * once;
}, "steps"_a);
// 3. A Python callable handed to C++ threads: each call takes the GIL
m.def("map_in_threads", [](nb::callable f, int n) {
const snicholls::python::python_function<int(int)> fn(f);
std::vector<int> out(static_cast<std::size_t>(n));
std::vector<std::thread> threads;
for (int i = 0; i < n; ++i)
threads.emplace_back([&, i] {
try { // no exception may leave a thread (the Python callable may raise)
out[static_cast<std::size_t>(i)] = fn(i);
} catch (...) {
out[static_cast<std::size_t>(i)] = -1;
}
});
for (auto& t : threads)
t.join();
});
int sum = 0;
for (const int x : out)
sum += x;
return sum;
}, "f"_a, "n"_a);
A Python callable as a C++ callable of a fixed signature, safe to copy, call and destroy on any threa...
Definition gil.hpp:125
::nanobind::call_guard<::nanobind::gil_scoped_release > release_gil
nanobind's call guard that releases the GIL for the duration of a bound call.
Definition gil.hpp:92
decltype(auto) without_gil(F &&f)
Runs f() with the GIL released and returns its result.
Definition gil.hpp:102
Relationships
  • nanobind's gil_scoped_release / gil_scoped_acquire / call_guard, which these name.
  • errors.hpp: a C++ exception thrown with the GIL released is translated after nanobind takes it back.
  • Group: snicholls::python - nanobind helpers.
Guarantees and contracts
  • without_gil(f) and with_gil(f) are exception-neutral: an exception from f propagates after the GIL state is restored.
  • python_function holds a strong reference; copying and destroying take the GIL, so it may be copied and destroyed on any thread. Calling it from a thread that already holds the GIL is fine (re-entrant).
  • Not for free-threaded Python builds (no GIL to release); the package is built for the GIL-ful stable ABI.
Errors
A Python exception raised by the callable becomes nanobind::python_error, which nanobind turns back into the same Python exception when it reaches the binding. A result that does not convert to R is nanobind::type_error (Python TypeError). R must be default-constructible.
Performance
Releasing and re-taking the GIL costs about 0.1 to 0.3 us; a python_function call adds the Python call itself. Measured as part of the call overhead in BENCHMARKS.md (tabular Shapley).
Tests and demos
  • Tests: tests/nanobind/gil_test.cpp (the test module), tests/nanobind/gil_test.py.
  • Demo: demos/nanobind/gil_demo.cpp, demos/nanobind/gil_demo.py; scripts/demos/gil_demo.sh.
Dependencies
CMake target snicholls::core_nanobind, inside a module built with nanobind_add_module (nanobind v3).
Known issues and gotchas
  • Never touch a nanobind::object inside without_gil - not even to copy or destroy it. Convert first.
  • A python_function called on a C++ thread can throw (nanobind::python_error); no exception may leave a thread, so catch it there, carry it back as a std::exception_ptr, and rethrow it on the calling thread after the join, with the GIL held again (tests/nanobind/gil_test.cpp, call_from_threads).
  • release_gil with an argument that is a Python object (nanobind::object, nanobind::callable) is a crash waiting to happen: the object is destroyed after the call, with the GIL held again, but used during it without.
Status
Experimental, pre-1.0.

Definition in file gil.hpp.