Skip to content

Commit 3637a3c

Browse files
committed
Use native API for holding GIL when Python functor is being destructed
Don't use `gil_scoped_aquire` because it can result in deadlock.
1 parent 0814105 commit 3637a3c

File tree

1 file changed

+7
-5
lines changed

1 file changed

+7
-5
lines changed

include/pybind11/functional.h

+7-5
Original file line numberDiff line numberDiff line change
@@ -57,15 +57,17 @@ struct type_caster<std::function<Return(Args...)>> {
5757
// ensure GIL is held during functor destruction
5858
struct func_handle {
5959
function f;
60-
func_handle(function&& f_) : f(std::move(f_)) {}
61-
func_handle(const func_handle&) = default;
6260
~func_handle() {
63-
gil_scoped_acquire acq;
64-
function kill_f(std::move(f));
61+
PyGILState_STATE gstate;
62+
gstate = PyGILState_Ensure();
63+
{
64+
function kill_f(std::move(f));
65+
}
66+
PyGILState_Release(gstate);
6567
}
6668
};
6769

68-
value = [hfunc = func_handle(std::move(func))](Args... args) -> Return {
70+
value = [hfunc = func_handle{func}](Args... args) -> Return {
6971
gil_scoped_acquire acq;
7072
object retval(hfunc.f(std::forward<Args>(args)...));
7173
/* Visual studio 2015 parser issue: need parentheses around this expression */

0 commit comments

Comments
 (0)