我知道,我知道,我的消息的标题可能看起来具有挑衅性,因为 boost :: mutex有意义地不公开锁定/解锁(为了避免死亡锁)。boost :: mutex /如何测试一个互斥锁是否被锁定
但是这些方面的boost文档很短(至少可以这么说),所以我在问以下用例是否有人能帮助我。
假设你有一个类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 !
}
};
我尝试(没有成功),以实现基于增强版本::互斥
//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;
};
我完全错了吗?任何人都可以告诉我,这应该怎么做与boost :: mutex?
谢谢!
为什么被破坏你的对象,而另一个线程仍然有一个指针指向它? – 2009-12-15 01:38:28
不直接回答问题,你可以取消注册引发'OnTimer()'调用作为你的析构函数的第一步吗?诚然,呼叫仍然可以通过“同时”异步进行,但尚不清楚为什么此对象正在遭受破坏仍然是这些回调的目标。 – seh 2009-12-15 01:40:30
@Anon:同意,这是一种代码味道。尽管如此,我仍然对这个答案感兴趣。 @ Seh:您的评论基于相同的代码气味。但是,我不能直接取消它,而不会破坏封装。 – 2009-12-15 01:44:58