5

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 Answers1

17

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(); }
};
juanchopanza
  • 223,364
  • 34
  • 402
  • 480
  • And what's the point of passing `this` twice? I think the OP just misunderstood what member functions are... – Kerrek SB May 23 '13 at 18:42
  • 1
    Nope, I know what's a member function ;). We don't need "this" twice. when using a static function you don't need to give this reference. But with a none-static it is needed. That way in the function you can use directly this keyword. So you should remove from execute function the parameter since we can access this. –  May 23 '13 at 18:56
  • @pikaille correct. But if you could call `execute` with different `PipelineJob` instances. In this example I use `this` twice, but it doesn't have to be like that. You could have pointers to two different `PipelineJob` instances. – juanchopanza May 23 '13 at 19:12
  • @Yakk some concern about the object not being fully constructed when the thread starts. I don't know what `execute` does with `this`. Probably just being over cautious. – juanchopanza May 23 '13 at 19:14
  • @juanchopanza Yes there could be a use case, in mine I just needed the this reference, so the second this becomes useless. –  May 23 '13 at 19:51