I am writing a modular Python program for data acquisition. I compiled different codes for cameras (the "producers") and for the data analyzing (the "consumers"), and made Python modules from them using PyBind11. Each module has a C++ method Start()
, exposed to Python, which starts independent operations in separate threads.
My Python script loads one of the "producer/camera" module and one of the "consumer/analyzer" module. It allocates memory by creating a numpy array and passes the pointers to that memory both to the producer and the consumer, using PyBind11 to expose the underlying pointers. Now the producer writes on that buffer and the consumer reads from that buffer. That works well.
Now, to avoid busy waiting from the consumer, I would also like to share mutex and condition_variable betweens the modules. However, PyBind11 does not seem to have casting predefined for std::mutex
and std::condition_variable
.
How can I simply create a mutex and a condition_variable in Python and pass it to python modules written in C++ ? Or, how can I create a mutex and a condition_variable in the producer module and pass to the consumer module a pointer towards them through Python ?
I've tried the following on the PyBind11 bindings.cpp
side and the code compiles :
MyClass::define_cv_mutex(std::condition_variable *cv, std::mutex *mtx)
{
cv_pointer = cv; //cv_pointer is member of MyClass
mtx_pointer = mtx; //mtx_pointer is member of MyClass
}
PYBIND11_MODULE(bindings, m){
pybind11::class_<MyClass>(m, "MyClass")`
.def(pybind11::init<>())`
.def("define_cv_mutex",&MyClass::define_cv_mutex)`
}
On the Python side I naively tried :
mutex = threading.Lock()
cv = threading.Condition()
A = MyClass()
A.define_cv_mutex(cv,mutex)
but it does not work
TypeError: define_cv_mutex(): incompatible function arguments. The following argument types are supported: 1. (self: MyModule.bindings.MyClass,arg0: std::condition_variable, arg1: std::mutex) -> None Invoked with: <MyModule.bindings.MyClass object at 0x7f0d7700bdf0>,<Condition(<unlocked _thread.RLock object owner=0 count=0 at 0x7f0d5f995200>, 0)>, <unlocked _thread.lock object at 0x7f0d5928a940>