繁体   English   中英

Boost为同一个线程获取多个锁

[英]Boost get multiple locks for the same thread

我有一个需要复习的基本样本(C ++)。

假设我有一个函数PublicFunc(),另一个叫做PrivateFunc()。 我想仔细同步它们。 但是PrivateFunc有时可以调用PublicFunc,这意味着我们从同一个线程调用它。 这会导致阻塞,我想解决它。

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();
}

来自boost库的哪个互斥锁或锁是正确的? 谢谢!

mutex只能锁定一次; 在锁定互斥锁时锁定互斥锁的任何调用都将阻塞,即使锁定互斥锁的线程是由锁定互斥锁的线程进行的。

如果您希望能够在同一个线程上多次锁定互斥锁,请使用recursive_mutex

或者,考虑重新组织代码,以便您拥有一组(私有)成员函数,这些函数假定互斥锁已被锁定,并且所有其他函数都委托给这些函数。 这可以使代码更清晰,并且可以更容易验证同步是否正确。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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