C ++ 11:使用成员函数启动线程,并将其作为参数

时间:2013-05-23 16:00:20

标签: c++ multithreading c++11 stdthread

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

错误1错误C2064:term不评估为带有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);
    }
};

我尝试了很多变化,现在任何一个如何解决这个问题?

1 个答案:

答案 0 :(得分:16)

为简单起见,删除模板和指针,这或多或少是您想要的:

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

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

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

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