Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c++ sharing single class object between multiple processes

Tags:

c++

object

share

I have a relatively complex class in c++. It works perfectly when used within one process. However, now I want multiple processes to be able to share one object instance of this class. One process (Master) will access read and write functions of the object, while the other 2 processes (Slave) will only use the read functions. I want to modify the class as little as possible. So far I have considered singletons and shared memory, but neither seems ideal or straightforward. This is a research application that will only ever be used by me on Linux. What is the simplest possible solution?

Thanks so much!

Edit: To be absolutely clear, the asker is interested in sharing an object across multiple processes, not threads.

like image 528
user1971455 Avatar asked May 30 '13 20:05

user1971455


People also ask

Can 2 processes share memory?

Context switching between processes is more expensive. Processes don't share memory with other processes. Threads share memory with other threads of the same process.

How do I share data between processes?

To share big data: named shared-memory The fastest way to handle this is to create a file mapping object, map the file object into memory space, notify the parent process of the file mapping handle and data size, and then dump the data to the mapped buffer for the parent process to read.


2 Answers

Inter-process communication is never simple. You may want to use a library for IPC/RPC and expose only the function the slaves use to read data, not the entire class.

I can't give you any good recommendations because I have never found a library that made it simple and I don't have much experience with it.

like image 92
Minthos Avatar answered Oct 23 '22 13:10

Minthos


One idea might be to use socket or a socket library to share the data amongst the processes. A library which seems to be very handy for that might be ØMQ. You can also try to use Boost::Asio which is a bit more complex.

You can find a small example for ØMQ here.

like image 1
mistapink Avatar answered Oct 23 '22 12:10

mistapink