I am trying to modify a python program to be able to communicate with a C++ program using shared memory. The main responsibility of the python program is to read some video frames from an input queue located in shared memory, do something on the video frame and write it back to the output queue in shared memory.
I believe there are few things I need to achieve and it would be great if someone can shed some light on it:
Shared memory: In C/C++, you can use functions like shmget
and shmat
to get the pointer to the shared memory. What is the equivalent way to handle this in python so both python and C++ program can use the same piece of shared memory?
Synchronization: Because this involves multi-processing, we need some sort of locking mechanism for the shared memory in both C++ and python programs. How can I do this in python?
Many thanks!
Perhaps shmget
and shmat
are not necessarily the most appropriate interfaces for you to be using. In a project I work on, we provide access to a daemon via a C and Python API using memory mapped files, which gives us a very fast way of accessing data
The order of operations goes somewhat like this:
door_call()
to tell the daemon to create a shared memory regionopen()
s and then mmap()
s that filedoor_return()
mmap()
s the file descriptor and associates consecutively-placed variables in a structure with that fdOur clients make use of a library to handle the first 5 steps above; the library comes with Python wrappers using ctypes to expose exactly which functions and data types are needed.
For your problem space, if it's just the python app which writes to your output queue then you can track which frames have been processed just in the python app. If both your python and c++ apps are writing to the output queue then that increases your level of difficulty and perhaps refactoring the overall application architecture would be a good investment.
Thanks for your suggestions. Please can you briefly explain how can I implement the
door_call()
anddoor_return()
myself as apparently they are Oracle's function? Is it a kind of signal, unix socket or something else?I spent some time to have a look on CPython and found that we can directly call python functions directly using Py_xxx. Would it be more efficient to pass a video frame directly to Py_xxx(frame) as an argument rather than using shared memory, and obtained the processed frame from the return value of this function? Or any drawback on this?
Re your question about
door_call()
anddoor_return()
: I'm uncertain whether those functions have been fully implemented for linux; rampant.org/doors/index.html is a bit out of date. You might be better off using unix domain sockets instead.CPython might well provide you with the functionality you need. You would need to assess just how efficient (and elegant, frankly) it is given your use-case and functionality requirements.