c++scoped-lockboost-mutex

"Nested" scoped_lock


My shortened, simplified class looks as follows:

class A
{
    public:
    // ...
    methodA();
    methodB();

    protected:
    mutable boost::mutex m_mutex;
    sometype*  m_myVar;
}

A::methodA( int someParam )
{
    boost::mutex::scoped_lock myLock(m_mutex);
    m_myVar->doSomethingElse();
}

A::methodB( int someParam )
{
    boost::mutex::scoped_lock myLock(m_mutex);
    m_myVar->doSomething();
    this->methodA(someParam);
}

I would like to synchronize access on m_myVar. When calling A::methodB(), the thread runs into the lock with the same mutex twice and obviously blocks on the first line of A::methodA()

Is there any way to make scoped_lock not blocking the same thread when passing again?

Sure, I simply could call m_mutex.unlock(). But this would free the other threads waiting on the lock as well - which is absolutely not what I want.

Any idea?

Best regards Tobias


Solution

  • This is what boost::recursive_mutex for it allows to obtain the lock by the same thread without deadlocking several times. Use it instead of boost::mutex