したがって、クラスオブジェクトをパラメーターとしてスレッドを生成するクラスがあります。次に、スレッドでメンバー関数を呼び出します。同期には 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());
}