从std :: thread访问类变量

Har*_*Boy 3 c++ multithreading c++11

我有以下类开始一个新的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;
}
Run Code Online (Sandbox Code Playgroud)

我怎样才能做到这一点??

Mik*_*our 5

如果this要从线程函数中进行访问,则它不应该是静态的:

void MyThread();
Run Code Online (Sandbox Code Playgroud)

现在你可以简单地传递this第二个thread构造函数参数,就像你试过的那样; 但是,作为非静态成员,您需要限定其名称:

m_Thread= new std::thread(&SingletonClass::MyThread, this);
Run Code Online (Sandbox Code Playgroud)

或者,您可能会发现lambda更容易阅读:

m_Thread= new std::thread([this]{MyThread();});
Run Code Online (Sandbox Code Playgroud)

但是你不应该用指针来捣乱new; 使成员变量成为一个thread对象并在初始化列表中初始化它:

SingletonClass::SingletonClass() :
    m_Continue(true), m_Thread([this]{MyThread();})
{}
Run Code Online (Sandbox Code Playgroud)

确保m_Thread在其访问的任何其他成员之后声明; 并确保在析构函数中或之前停止并加入线程.

最后,m_Continue应该是std::atomic<bool>为了将它设置在一个线程上并在具有明确定义的行为的另一个线程上读取它.