Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Deleting boost interprocess_mutex when other process might be using it

I'm trying to use interprocess_mutex with managed_windows_shared_memory. In my project, multiple processes create an instance of class A in the following code.

using namespace boost::interprocess;

class A
{
    managed_windows_shared_memory* _shm;
    interprocess_mutex* _mtx;
}
A::A()
{
    _shm = new managed_windows_shared_memory{ open_or_create, "shm", 1024 };
    _mtx = _shm->find_or_construct<interprocess_mutex>("mtx")();
}
A::~A()
{
    delete _mtx;
    delete _shm;
}

I can see that it is safe to call delete _shm; in ~A(), since managed_windows_shared_memory will be destroyed only when every process using it destroys the managed_windows_shared_memory object, as written in the doc.

However, I'm not sure if it is safe to call delete _mtx; in ~A(). In the doc for interprocess_mutex, it is not mentioned that whether it is still destroyed or not even if other processes have objects referring to it.

I've searched this and I'm guessing that my option is to use boost::interprocess::shared_ptr in this case. Am I right here? Is this the option that I should take?

like image 969
nglee Avatar asked Jun 05 '18 02:06

nglee


1 Answers

From the documentation:

Both processes share the same object

(emphasis in the original).

Obviously you cannot destroy an object while some other code might still access it, even if it's code in another process, because both processes share the same object.

Note the situation with the shared memory pointer is different. The shared memory object is not shared between processes. The region of memory it manages is, but the C++ object itself is private to the process.

The mutex, on the other hand, lives in that shared memory region and so is shared.

Unless you want to reuse the memory occupied by the mutex, you don't need to delete _mtx at all, so don't bother with shared pointers or reference counters. Deleting the shared memory object will just unmap everything inside the corresponding memory segment, as if it was never there.

like image 56
n. 1.8e9-where's-my-share m. Avatar answered Nov 14 '22 10:11

n. 1.8e9-where's-my-share m.