c++boostsynchronizationinterprocessboost-interprocess

Avoid locking inside of boost::interprocess::managed_shared_memory


I want to create a managed_shared_memory that is going to be created and written to by process A and read from by process B. So far I managed to implement the functionality I want, but I realized that when a process crashed during a .find or .construct operation, the mutex will not be unlocked (so it is not a robust mutex). The documentation says that there is a way to disable the internal locking of the shared memory. This would be great because I want to use an interprocess_condition anyway.

The synchronization type (MemoryAlgorithm::mutex_family) to be used in all allocation operations. This allows the use of user-defined mutexes or avoiding internal locking (maybe code will be externally synchronized by the user).

The problem is I am at a total loss on how to change the locking behavior of the managed_shared_memory object. I looked through its constructors but I cannot find a solution to this problem.

I am restricted to using boost 1.60 and I am writing for a Linux device, although any portable solution would be preferred since I am using boost anyway.


Solution

  • The problem is I am at a total loss on how to change the locking behavior of the managed_shared_memory object. I looked through its constructors but I cannot find a solution to this problem.

    Okay, I think the choice is hard-coded - for good reason. Like I said in my comment there is no safe way to access managed memory segments from different processes without synchronization on the segment metadata.

    Now, if you're absolutely sure you want to (you're in shooting-yourself-in-the-foot-with-enough-rope-to-hang-yourself territory) you should probably manually mount a managed external buffer:

    Managed External Buffer: Constructing all Boost.Interprocess objects in a user provided buffer

    You could of course still put it in an (unmanaged) mapped_region of Mappable Object (like shared_memory_object).

    You can parameterize your managed external buffer as you wish, but the default already doesn't lock:

    typedef basic_managed_external_buffer <
       char,
       rbtree_best_fit<null_mutex_family, offset_ptr<void> >,
       flat_map_index
       >  managed_external_buffer;