Manan Shah
Manan Shah

Reputation: 377

how to check whether pthread_mutex_t is locked or not

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

Upvotes: 3

Views: 4257

Answers (2)

Rocker
Rocker

Reputation: 25

use pthread_mutex_trylock It will give busy state if mutex is already locked. If its not locked then it will lock it. After this unlock mutex. pthread_mutex_unlock(pthread_mutex_t *mutex);

Upvotes: 1

Jerry Coffin
Jerry Coffin

Reputation: 490663

Write a tiny RAII-style locker class:

class lock { 
    pthread_mutex_t &mutex;
public:   
    lock(pthread_mutex_t &m) :mutex(m) { pthread_mutex_lock(&mutex); }
    ~lock() { pthread_mutex_unlock(&mutex); }
};

Then write your code something like this:

void Method1()
{
    try
    {
        { 
            lock l(syncLock);
            statement1;
            statement2;
         }
         statement3;
         statement4;    
    }
    catch(exception& e)
    {
    log error
    }
}

When you exit from the scope where you defined the lock, the lock will be destroyed via the destructor, thus calling pthread_mutex_unlock. That happens whether you exit the scope normally or via an exception. When you enter the exception handler, you know the mutex has been unlocked.

Note that C++11 has this built into the standard library as std::lock_guard (and has a number of mutex types to use with it).

Upvotes: 6

Related Questions