Am quite sure this is a naive question but still going to ask it nevertheless since I couldn't find much help on net. I am writing a c++ code using pthreads . The following is an outline of one of the methods
void Method1()
{
try
{
pthread_mutex_lock(&syncLock);
statement1;
statement2;
pthread_mutex_unlock(&syncLock);
statement3;
statement4;
}
catch(exception& e)
{
log error
}
}
where syncLock is of type pthread_mutex_t
and is initialized using the default initialization.
My question is that if an exception is thrown in the statement2 of the method then the control passes directly to the catch statement. In that case my mutex remains locked. But I also cant simply write an unlock statement in the catch block since if the exception came from statement 3 then the mutex has been unlocked and calling unlock on an already unlocked mutex results in undefined behavior.
So is there a way I can check whether the mutex has been unlocked or not in the catch statement. Or, is there a C# style lock statement alternative available in c++ so I am sure that the lock is released even if an exception is thrown from within that block
I am not inclined to use libraries for this purpose. A simple custom solution will be much appreciated
Thanks