Skip to content

Commit b66623f

Browse files
committed
Fix async Python functors invoking from multiple C++ threads (#1587)
Ensure GIL is held during functor destruction.
1 parent 83113a0 commit b66623f

File tree

1 file changed

+13
-2
lines changed

1 file changed

+13
-2
lines changed

include/pybind11/functional.h

+13-2
Original file line numberDiff line numberDiff line change
@@ -54,9 +54,20 @@ struct type_caster<std::function<Return(Args...)>> {
5454
}
5555
}
5656

57-
value = [func](Args... args) -> Return {
57+
// ensure GIL is held during functor destruction
58+
struct func_handle {
59+
function f;
60+
func_handle(function&& f_) : f(std::move(f_)) {}
61+
func_handle(const func_handle&) = default;
62+
~func_handle() {
63+
gil_scoped_acquire acq;
64+
function kill_f(std::move(f));
65+
}
66+
};
67+
68+
value = [hfunc = func_handle(std::move(func))](Args... args) -> Return {
5869
gil_scoped_acquire acq;
59-
object retval(func(std::forward<Args>(args)...));
70+
object retval(hfunc.f(std::forward<Args>(args)...));
6071
/* Visual studio 2015 parser issue: need parentheses around this expression */
6172
return (retval.template cast<Return>());
6273
};

0 commit comments

Comments
 (0)