简体   繁体   中英

Boost get multiple locks for the same thread

I have a basic sample which needs review (C++).

Let's say I have a function PublicFunc(), and another one called PrivateFunc(). I'd like to synchronize them carefully. But PrivateFunc can sometimes call PublicFunc as well what means we are calling it from the same thread. This causes blocks, and I'd like to solve it.

mutable boost::mutex m;

void PublicFunc() {
 m.lock();
 //Here it blocks, but why?
 //What I need is to get the lock if this func was called from PrivateFunc(), so exactly from the same thread.
 //But! It should definitely block on calling PublicFunc from outside while we are for example in the 'OtherPrivateFunc'.

 //Do some stuff

 //this is not necessary
 m.unlock(); 
}

void PrivateFunc() {
 m.lock();

 PublicFunc();

 OtherPrivateFunc();

 m.unlock();
}

Which mutex or lock is the right one from the boost library? Thank you!

A mutex may only be locked once; any call to lock the mutex while it is locked will block, even if the attempt to lock the mutex is made by the thread that holds the lock on the mutex.

If you want to be able to lock a mutex multiple times on the same thread, use recursive_mutex .

Alternatively, consider reorganizing your code so that you have one set of (private) member functions that assume the mutex is locked, and have all other functions delegate to these. This can make the code clearer and can make it easier to verify that the synchronization is correct.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM