Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Acquire the GIL when calling Python callbacks in the MessageQueue #1197

Merged
merged 1 commit into from
Dec 18, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 18 additions & 8 deletions bindings/python/src/MessageQueueBindings.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -40,15 +40,25 @@ void MessageQueueBindings::bind(pybind11::module& m, void* pCallstack) {

// Bind DataOutputQueue
auto addCallbackLambda = [](MessageQueue& q, py::function cb) -> int {
pybind11::module inspect_module = pybind11::module::import("inspect");
pybind11::object result = inspect_module.attr("signature")(cb).attr("parameters");
pybind11::module inspectModule = pybind11::module::import("inspect");
pybind11::object result = inspectModule.attr("signature")(cb).attr("parameters");
auto numParams = pybind11::len(result);
if(numParams == 2) {
return q.addCallback(cb.cast<std::function<void(std::string, std::shared_ptr<ADatatype>)>>());
} else if(numParams == 1) {
return q.addCallback(cb.cast<std::function<void(std::shared_ptr<ADatatype>)>>());
} else if(numParams == 0) {
return q.addCallback(cb.cast<std::function<void()>>());

if (numParams == 2) {
return q.addCallback([cb](std::string msg, std::shared_ptr<ADatatype> data) {
pybind11::gil_scoped_acquire gil;
cb(msg, data);
});
} else if (numParams == 1) {
return q.addCallback([cb](std::shared_ptr<ADatatype> data) {
pybind11::gil_scoped_acquire gil;
cb(data);
});
} else if (numParams == 0) {
return q.addCallback([cb]() {
pybind11::gil_scoped_acquire gil;
cb();
});
} else {
throw py::value_error("Callback must take either zero, one or two arguments");
}
Expand Down
Loading