C ++ 11:启动具有成员函数的线程,并将其作为参数

编程入门 行业动态 更新时间:2024-10-28 18:35:07
本文介绍了C ++ 11:启动具有成员函数的线程,并将其作为参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

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

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:启动具有成员函数的线程,并将其作为参数

本文发布于:2023-10-25 03:06:47,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1525740.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:线程   函数   成员   参数   并将其

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!