【发布时间】:2014-09-25 16:36:06
【问题描述】:
我有以下类启动一个新的 std::thread。我现在希望线程访问该类的成员变量。到目前为止,我无法弄清楚如何做到这一点。 在我的 MyThread 函数中,我想检查 m_Continue。
我尝试在创建线程时传入“this”,但出现错误:
错误 1 错误 C2197: 'void (__cdecl *)(void)' : 调用 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<bool>或使用std::mutex保护对其的访问。
标签: c++ multithreading c++11