我有以下类开始一个新的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