Search code examples
c++boostipcshared-memory

New instance of class in a shared memory segment C++


I'm actually trying to step-up in thread, process and shared memory in C++ but I'm actually stuck with my Inter Process Communication.

I decided to use a message queue cause i already used some in past project but never with multiple process.

Here is my problem, I can't get register events from different process. I think that initialize my message queue in a share memory segment would fix the problem but I can't figure out how to "force" the new instance of my class to be in my shared memory segment

Because I start with shared memory in C++, I use boost Simple Exemple

Ideally what i would like to have would be something like :

int main (void)
{
    shared_memory_object shm (open_or_create, "MySharedMemory", read_write);

    // initialise shm using boost Simple Exemple

    shmPtr = region.get_address();

    // initialise message queue named msgQueue in my shared memory segment

    msgQueuePtr = &msgQueue;

}

At the end, shmPtr would be equal to msgQueuePtr.
Any help would be appreciate.


Solution

  • I would use a managed memory segment so you can "just" construct your types in shared memory (note: be sure they are POD or take a shared-memory allocator to properly handle any dynamic allocation/reference).

    #include <boost/interprocess/managed_shared_memory.hpp>
    #include <iostream>
    
    struct MyQueue { /* */ };
    
    namespace bip = boost::interprocess;
    
    int main() {
        bip::managed_shared_memory msm(bip::open_or_create, "test", 10ul<<30); // 10 MiB
        MyQueue& q = *msm.find_or_construct<MyQueue>("queue_instance")();
    }
    

    Here's a bigger demo complete with a queue implementation + locking etc. Boost shared memory and synchronized queue issue/crash in consumer process

    BONUS

    Boost Interprocess has a complete message_queue implementation: https://www.boost.org/doc/libs/1_73_0/doc/html/boost/interprocess/message_queue.html

    So, when in doubt, I suggest to use that.