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

喜夏-厌秋 提交于 2019-12-05 03:02:00

问题


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

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?


回答1:


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(); }
};


来源:https://stackoverflow.com/questions/16718663/c-11-start-thread-with-member-function-and-this-as-parameter

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!