c++线程函数

线程函数的参数中是没有this指针参数的。类内的函数默认会在参数末尾添加this指针,不满足线程函数的要求。

全局函数(类外的函数)、static修饰的静态函数都可以消除默认添加的this指针。

所以,线程函数放类内需加static修饰,或者直接放类外

注意:静态成员函数在类外实现时候无须加static关键字,否则是错误的。

例如,*.h头文件中,线程函数放类内,则写成 static void MyThreadFunction();

在对应的*.cpp中,写成void 类名::MyThreadFunction();

 

【类的成员函数作为线程函数】

方式一:&类::成员函数, 类对象指针 

TaskQueue taskQueue;
std::thread t(&TaskQueue::ExecuteTasks,&taskQueue);

 方式二:std::bind(&类::成员函数, 类对象指针) 

std::function<void()> func = std::bind(&TaskQueue::ExecuteTasks, &taskQueue);
std::thread t(func);

  

【参考】

为什么类中的线程函数必须要声明静态?

c/c++基础(二十四) 静态属性与静态方法

c++ bind this 实现成员函数代替静态函数

posted @ 2019-12-18 18:59  夕西行  阅读(299)  评论(0编辑  收藏  举报