invoking std::function inside std::thread hangs #391
-
Hi, I've been using nanobind in a few projects and it's been working great so far. One project has a function that accepts a For example: NB_MODULE(example, m) {
// invoke the function directly
m.def("foo", [](const std::function<float(float)> & func) {
return func(4.2f);
});
// invoke the function from inside a std::thread
m.def("bar", [](const std::function<float(float)> & func) {
float answer = 0;
std::thread thr([&](){ answer = func(4.2f); });
thr.join();
return answer;
});
} When testing this with a simple python script import example
def f(x):
return x + 3
print("running foo(f)")
print(example.foo(f))
print("running bar(f)")
print(example.bar(f))
print("done") I get the following output:
That is, the direct evaluation of the python-to- Is this an inherent GIL limitation, a bug with nanobind or something else entirely? Thank you, Sam |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
That's a GIL-related deadlock. |
Beta Was this translation helpful? Give feedback.
That's a GIL-related deadlock.
bar
holds the GIL, and then your thread is trying to re-enter it when calling the Python functionfunc
. If those two thread were completely decoupled, then they would simply wait for each other. But you calljoin()
withinbar
. This should work if you drop theGIL
withinbar
by addingnb::gil_scoped_release guard
. However, note that you're not allowed to call other nanobind functions within that scope since they assume that the GIL is held.