所以我有一个类生成一个以类对象作为参数的线程。然后在线程中我调用了一个成员函数。我使用 Critical_Sections 进行同步。
那么这个实现是线程安全的吗?因为只有成员是线程安全的而不是类对象。
class TestThread : public CThread
{
public:
virtual DWORD Work(void* pData) // Thread function
{
while (true)
{
if (Closing())
{
printf("Closing thread");
return 0;
}
Lock(); //EnterCritical
threadSafeVar++;
UnLock(); //LeaveCritical
}
}
int GetCounter()
{
int tmp;
Lock(); //EnterCritical
tmp = threadSafeVar;
UnLock(); //LeaveCritical
return tmp;
}
private:
int threadSafeVar;
};
.
.
.
TestThread thr;
thr.Run();
while (true)
{
printf("%d\n",thr.GetCounter());
}
最佳答案
如果成员是您的关键部分,您应该只锁定对它的访问。
顺便说一句,你可以像这样实现一个储物柜:
class Locker
{
mutex &m_;
public:
Locker(mutex &m) : m_(m)
{
m.acquire();
}
~Locker()
{
m_.release();
}
};
你的代码看起来像:
mutex myVarMutex;
...
{
Locker lock(myVarMutex);
threadSafeVar++;
}
...
int GetCounter()
{
Locker lock(myVarMutex);
return threadSafeVar;
}
关于c++ - 成员变量的线程安全访问,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19710526/