我想知道启动一个C++类成员的pthread 的最佳方法是什么?我自己的方法作为答案......
这可以通过使用boost库来完成,如下所示:
#include// define class to model or control a particular kind of widget class cWidget { public: void Run(); } // construct an instance of the widget modeller or controller cWidget theWidget; // start new thread by invoking method run on theWidget instance boost::thread* pThread = new boost::thread( &cWidget::Run, // pointer to member function to execute in thread &theWidget); // pointer to instance of class
笔记:
这使用普通的类成员函数.无需添加额外的静态成员,这会使您的类接口混乱
只需在启动线程的源文件中包含boost/thread.hpp即可.如果你刚刚开始使用boost,那么所有其他大型和令人生畏的软件包都可以忽略.
在C++ 11中,你可以做同样但没有提升
// define class to model or control a particular kind of widget class cWidget { public: void Run(); } // construct an instance of the widget modeller or controller cWidget theWidget; // start new thread by invoking method run on theWidget instance std::thread * pThread = new std::thread( &cWidget::Run, // pointer to member function to execute in thread &theWidget); // pointer to instance of class
我通常使用类的静态成员函数,并使用指向该类的指针作为void*参数.然后,该函数可以执行线程处理,或者使用类引用调用另一个非静态成员函数.然后,该函数可以引用所有类成员而不会出现笨拙的语法.
你必须使用void*参数来引导它:
class A { static void* StaticThreadProc(void *arg) { return reinterpret_cast(arg)->ThreadProc(); } void* ThreadProc(void) { // do stuff } }; ... pthread_t theThread; pthread_create(&theThread, NULL, &A::StaticThreadProc, this);