C++ 11 : Start thread with member function and this as parameter

最后都变了- 提交于 2019-12-03 20:45:00

Removing the templates and the pointers for simplicity, this is more or less what you would want:

class PipelineJob 
{
private:
    std::thread thread_;
    void execute(PipelineJob* object) { ..... }
public:
    PipelineJob()
    {
      thread_ = std::thread(&PipelineJob::execute, this, this);
    }
    ~PipelineJob() { thread_.join(); }
};

Note that this is passed two times to the std::thread constructor: once for the member function's implicit first parameter, the second for the visible parameter PipelineJob* object of the member function.

If your execute member function does not need an external PipelineJob pointer, then you would need something like

class PipelineJob 
{
private:
    std::thread thread_;
    void execute() { ..... }
public:
    PipelineJob()
    {
      thread_ = std::thread(&PipelineJob::execute, this);
    }
    ~PipelineJob() { thread_.join(); }
};
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!