我正在致力于重构一些存在死锁的遗留代码。主要有两个根本原因:
1)同一线程多次锁定同一互斥锁,这应该不难解决;2)代码偶尔会调用用户定义的函数,这些函数可以在顶层输入相同的代码。在调用用户定义的函数之前,我需要锁定互斥锁,但我可能会再次执行相同的代码,这将导致死锁情况。所以,我需要一些机制来告诉我互斥量已经被锁定了,我不应该再次锁定它。有什么建议吗?
下面是代码功能的(非常)简要的总结:
class TreeNode {
public:
// Assign a new value to this tree node
void set(const boost::any& value, boost::function<void, const TreeNode&> validator) {
boost::upgrade_lock<boost::shared_mutex> lock(mutexToTree_);
// call validator here
boost::upgrade_to_unique_lock<boost::shared_mutex> ulock(lock);
// set this TreeNode to value
}
// Retrieve the value of this tree node
boost::any get() {
boost::shared_lock<boost::shared_mutex> lock(mutexToTree_);
// get value for this tree node
}
private:
static boost::shared_mutex mutexToRoot_;
};问题是验证器函数可以调用get(),从而将mutexToRoot_锁定在同一线程上。我可以将mutexToRoot_修改为递归互斥锁,但这将阻止其他线程在get()操作期间读取树,这是不想要的行为。
发布于 2017-08-09 11:47:50
由于C++11,您可以使用std::recursive_mutex,它允许拥有线程调用lock或try_lock而不会阻塞/报告故障,而其他线程将在try_lock上的lock/receive false上阻塞,直到拥有线程调用unlock的次数与之前调用lock/try_lock的次数相同。
https://stackoverflow.com/questions/45580953
复制相似问题