我相信我已经很好地掌握了C++中多线程的基础知识,但是我一直无法得到关于在共享资源周围锁定互斥体的明确答案在构造函数或析构函数中。我的印象是你应该锁定在两个地方,但最近同事不同意。在构造函数和析构函数中锁定共享资源
class TestClass
{
public:
TestClass(const float input) :
mMutex(),
mValueOne(1),
mValueTwo("Text")
{
//**Does the mutex need to be locked here?
mValueTwo.Set(input);
mValueOne = mValueTwo.Get();
}
~TestClass()
{
//Lock Here?
}
int GetValueOne() const
{
Lock(mMutex);
return mValueOne;
}
void SetValueOne(const int value)
{
Lock(mMutex);
mValueOne = value;
}
CustomType GetValueTwo() const
{
Lock(mMutex);
return mValueOne;
}
void SetValueTwo(const CustomType type)
{
Lock(mMutex);
mValueTwo = type;
}
private:
Mutex mMutex;
int mValueOne;
CustomType mValueTwo;
};
当然一切都应该是通过初始化列表安全的,但对于构造函数中的语句:假装以下类是由多个线程访问?在析构函数中,执行非范围锁定会有好处,并且永远不会解锁(本质上只是调用pthread_mutex_destroy)?
当你说的“类”是在多个线程之间使用,我假设你的意思是TestClass类型的对象可能在多个线程中使用。在这种情况下,你仍然只创建一个对象,所以你不需要在构造函数中锁定。如果两个线程同时在构造函数中,则它们将创建2个独立的对象。锁定对象构造更合理,以确保(例如)在对象完成构建之前不使用mValueTwo。析构函数似乎应该锁定,以确保数据在被销毁时不被访问。 – Rollie 2012-07-25 15:09:45
@Rollie是的,我确实认为这个对象是共享的。所以,如果我创建了: – Brett 2012-07-25 15:17:32
@Rollie:在破坏的时候访问类是一个带有实例生命周期管理的错误 - 当发生这种情况时程序已经被破坏(如果它可以在破坏时被访问,它也可能在事后发生)。 – 2012-07-25 15:18:18