Nested scoped_lock

My shorthand, simplified class is 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() thread runs into the lock with the same mutex twice and, obviously, blocks the first line of A::methodA()

Is there a way to make scoped_lock not blocking one thread while re-passing?

Of course, I could just call m_mutex.unlock() . But this will free up other threads waiting for blocking, and this is not at all what I want.

Any idea?

Regards Tobias

+6
source share
3 answers

This is what boost::recursive_mutex for it allows you to obtain a lock on one thread without deadlock several times. Use it instead of boost::mutex

+12
source

There are different things. You can use a recursive mutex that can be retrieved several times in one thread, or you can split methodA into a private method with and without locks and a public method that locks and then calls the private implementation. Then methodB will call the internal implementation, holding the lock. Since this method is private, you control all uses, and you can make sure that the implementation method is called only when it is locked.

+4
source

You can use tryLock in method A, if the attempt failed, you should get the current threadId and continue execution only if the thread ID matches the threadid file that runs MethodB. Otherwise, if the attempt is successful, you can continue execution.

0
source

Source: https://habr.com/ru/post/899900/


All Articles