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

user1401072 picture user1401072 · May 23, 2013 · Viewed 24.4k times · Source

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?

Answer

juanchopanza picture juanchopanza · May 23, 2013

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