我知道,我知道,我的消息的标题可能看起来很挑衅,因为boost :: mutex目的不会暴露锁定/解锁(为了避免死锁).
然而,这些方面的提升文档非常简短(至少可以这么说),所以我想问是否有人可以在以下用例中帮助我.
假设你有一个类Foo,它有:
- 一个需要一些时间才能完成的析构函数
- 一个由不同线程调用的方法,但是在销毁期间不应该调用
class Foo
{
public:
virtual ~Foo()
{
//Time consuming operations here
}
//Method called by a timer belonging to a distinct class
void OnTimer()
{
//Other time consuming stuff. Should not be called during destruction !
}
};
Run Code Online (Sandbox Code Playgroud)
我尝试(没有成功)实现基于boost :: mutex的版本
//boost::mutex implementation
class Foo
{
public:
Foo()
{
}
virtual ~Foo()
{
{
boost::mutex::scoped_lock lock(mDisposingMutex);
//Time consuming operations here
}
}
//Method called by a timer belonging to a distinct class
void OnTimer()
{
{
//Imaginary code here: mutex::locked() method is private !!!
if ( ! mDisposingMutex.locked())
return;
}
//Other time consuming stuff. Should not be called during destruction !
}
private:
boost::mutex mDisposingMutex;
};
Run Code Online (Sandbox Code Playgroud)
我完全错了吗?谁能告诉我这应该用boost :: mutex做什么?
谢谢 !
如果您确实提交Lockable::lock()在析构函数体中使用,则可以使用您的OnTimer()函数Lockable::try_lock(),并且仅当该函数返回true时才继续.OnTimer()如果OnTimer()首先启动,这将使析构函数保持不变,但它仍然无法解决析构函数运行,完成和释放互斥锁,然后OnTimer()启动并成功获取互斥锁的问题.
这样的序列可能属于未定义的行为领域,但该诅咒不会阻止它发生.除了互斥锁之外还使用状态标志- 类似于我在上面的评论中描述的那样 - 可以让你检测后一种情况,并且OnTimer()在阅读标志之外不要做任何事情.但是,在某些时候,这只是将创可贴置于创可贴之上.