我相信我已经很好地处理了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;
};
Run Code Online (Sandbox Code Playgroud)
当然,通过初始化列表,一切都应该是安全的,但构造函数中的语句呢?在析构函数中,执行非作用域锁定是有益的,并且永远不会解锁(基本上只是调用pthread_mutex_destroy)?