C ++ 11:启动具有成员函数的线程,并将其作为参数 [英] C++ 11 : Start thread with member function and this as parameter
问题描述
使用此代码,我得到了错误:
Using this code, I got and error :
错误1错误C2064:term不评估为一个函数带1个参数c:\program files )\microsoft visual studio 11.0 \vc\include\functional 1152 1管道
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?
推荐答案
为了简单起见,删除模板和指针,这或多或少是你想要的:
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(); }
};
请注意, this
std :: thread
构造函数:一次为成员函数的隐式第一个参数,第二个为可见参数 PipelineJob * object
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.
如果您的执行
成员函数不需要外部 PipelineJob
指针,那么你将需要像
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(); }
};
这篇关于C ++ 11:启动具有成员函数的线程,并将其作为参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!