C++ 11:使用成员函数和 this 作为参数启动线程

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16718663/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 20:35:18  来源:igfitidea点击:

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

c++multithreadingc++11stdthread

提问by juanchopanza

Using this code, I got and error :

使用此代码,我得到了错误:

Error 1 error C2064: term does not evaluate to a function taking 1 arguments c:\program files (x86)\microsoft visual studio 11.0\vc\include\functional 1152 1 Pipeline

错误 1 ​​错误 C2064:术语未计算为采用 1 个参数的函数 c:\program files (x86)\microsoft visual studio 11.0\vc\include\functional 1152 1 Pipeline

class PipelineJob {
private:
    std::thread *thread;
    void execute(PipelineJob* object);
public:

    void execute(PipelineJob* object)
    {
    }

    PipelineJob()
    {
        this->thread = new std::thread(&PipelineJob::execute, this);
    }
};

I tried many variation, any one now how to solve this?

我尝试了很多变体,现在有人如何解决这个问题?

回答by juanchopanza

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 thisis passed two times to the std::threadconstructor: once for the member function's implicit first parameter, the second for the visible parameter PipelineJob* objectof the member function.

请注意,thisstd::thread构造函数传递了两次:一次用于成员函数的隐式第一个参数,第二次用于PipelineJob* object成员函数的可见参数。

If your executemember function does not need an external PipelineJobpointer, then you would need something like

如果您的execute成员函数不需要外部PipelineJob指针,那么您将需要类似

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