C++并发编程如何调用类内部函数
文章目录
C11之后,C++引入了多线程标准库thread,这里直接说如何在一个类的成员函数中使用多线程调用起他成员函数的问题。直接上答案。
#include <iostream>
#include <thread>
using namespace std;
class ThreadInClass {
public:
void threadFun() {
cout << "I am a method of ThreadInClass from thread : ." << this_thread::get_id() << endl;
}
void invokeThreadFun() {
thread call(&ThreadInClass::threadFun, ref(*this));
call.join();
}
};
int main() {
ThreadInClass threadClass;
threadClass.invokeThreadFun();
return 0;
}
以上代码中定义了一个ThreadInClass的类,其有两个函数,一个是用来在新的线程中执行的threadFun,一个是在主线程调用的invokeThreadFun,使用是只需要把this指针转换为引用传递给thread的构造函数即可。

评论
登录后参与技术讨论,分享你的经验与见解。
登录 / 注册暂无评论