我有以下類開始一個新的std ::線程。我現在想讓線程訪問類的成員變量。到目前爲止,我無法解決如何做到這一點。 在我的MyThread函數中,我想檢查m_Continue。從std :: thread訪問類變量
我試圖傳遞「這個」被創建,但我得到一個錯誤的線程時:
錯誤1個錯誤C2197:「無效(__cdecl *)(無效)」:對於呼叫c的參數太多:\ program files(x86)\ microsoft visual studio 11.0 \ vc \ include \ functional 1152 1 MyProject。
class SingletonClass
{
public:
SingletonClass();
virtual ~SingletonClass(){};
static SingletonClass& Instance();
void DoSomething();
private:
static void MyThread();
std::thread* m_Thread;
bool m_Continue;
};
SingletonClass::SingletonClass()
{
m_Continue = true;
m_Thread= new std::thread(MyThread, this);
}
void SingletonClass::MyThread()
{
while(this->m_Continue)
{
// do something
}
}
void SingletonClass::DoSomething()
{
m_Continue = false;
}
SingletonClass& SingletonClass::Instance()
{
static SingletonClass _instance;
return _instance;
}
int _tmain(int argc, _TCHAR* argv[])
{
SingletonClass& singleton = SingletonClass::Instance();
singleton.DoSomething();
return 0;
}
我該怎麼做?
無關:沒有理由動態地分配線程,'m_thread'可能僅僅是一個'的std :: thread'你分配:'m_thread = std :: thread {MyThread,this};'。而且,由於在SingletonClass :: m_Continue中的數據競爭,你的程序有未定義的行爲,因爲它可能會在生成的線程中被訪問,同時在主線程中被修改。您需要將其設爲'std :: atomic'或使用'std :: mutex'保護對它的訪問。 –
Casey
2014-09-25 16:45:28