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:
- Process A creates an Instance of the class, calls the function and locks it
- Process B creates an Instances of the class, calls the function but can't access code ( then waits e.g. )
- Process A finishes with the protected code and it gets unlocked
- Process B gains access to the protected code and locks it
- Process A deletes the Instance of the class -> the remove command is called
- Process C creates an Instance of the class, calls the function and can access the code since the remove command erased the Mutex --> Error!
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?