I have a class which can be created by multiple threads. But at one function the code needs to be protected, so I decided to use the boost interprocess mutex. Every class creates or opens the same Mutex in it's constructor:
MyClass::MyClass()
{
boost::interprocess::named_mutex m_Lock(
boost::interprocess::open_or_create, "myLock" );
}
So now there comes the point where the critical code part is called:
int MyClass::MyFunction()
{
boost::interprocess::scoped_lock<boost::interprocess::named_mutex> lock(
m_Lock, boost::interprocess::try_to_lock);
if(!lock)
{
return -1;
}
// else do some stuff here
}
To clean up after the function ( and like its described on the boost page ) I use the remove command in my class destructor:
MyClass::~MyClass()
{
boost::interprocess::named_mutex::remove("myLock");
}
Actually all this code works fine, but there is one concern I have:
As it is said in the description of the remove command :
Erases a named mutex from the system. Returns false on error. Never throws.
So that means the remove command just erases the Mutex out of the system - even if another thread has just locked it ( I tried this case already - it isn't locked then anymore ). So my problem is the following: For example I have 3 Threads ( A, B and C ) - now the following happens:
So now someone may say " Then don't call remove! " - Well is that possible? I mean since the named_mutex writes to the system I doubt it is erased without an explicit call, even if the program ends. Anyone has some help?
From the boost docs, the remove
call, is unnecessary. The destructor of named_mutex
will automatically take care indicating to the OS that the process no longer needs the resource. You're probably fine with just relying upon the built-in behavior of the destructor for cleanup.
If you explicitly call remove, you'll likely cause any other processes or threads attempting to use the named mutex to fail on any operations on the mutex. Depending on how your usage is orchestrated, this could either cause data races or crashing/exceptions being thrown in other processes.
~named_mutex();
Destroys *this and indicates that the calling process is finished using the resource. The destructor function will deallocate any system resources allocated by the system for use by this process for this resource. The resource can still be opened again calling the open constructor overload. To erase the resource from the system use remove().
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With