题
我想知道 最好的 启动作为 C++ 类成员的 pthread 的方法?我自己的方法如下作为答案......
解决方案
我通常使用类的静态成员函数,并使用指向类的指针作为 void * 参数。然后,该函数可以执行线程处理,或者使用类引用调用另一个非静态成员函数。然后,该函数可以引用所有类成员,而无需使用尴尬的语法。
其他提示
这可以通过使用 boost 库简单地完成,如下所示:
#include <boost/thread.hpp>
// 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 中你可以做同样的事情但没有 boost
// 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* 参数来引导它:
class A { static void* StaticThreadProc(void *arg) { return reinterpret_cast<A*>(arg)->ThreadProc(); } void* ThreadProc(void) { // do stuff } }; ... pthread_t theThread; pthread_create(&theThread, NULL, &A::StaticThreadProc, this);
我已经使用了上面列出的三种方法。当我第一次在 C++ 中使用线程时,我使用了 静态成员函数, , 然后 友元函数 最后是 BOOST 库. 。目前我更喜欢BOOST。在过去的几年里,我已经成为了一个相当“BOOST”的偏执者。
BOOST 之于 C++ 就像 CPAN 之于 Perl。:)
Boost库提供了复制机制,该机制有助于将对象信息传输到新线程。在另一个 boost 示例中, boost::bind 将使用指针进行复制,该指针也只是被复制。因此,您必须注意对象的有效性,以防止出现悬空指针。如果您实现了operator()并提供了一个复制构造函数并直接传递对象,则不必关心它。
一个更好的解决方案,可以避免很多麻烦:
#include <boost/thread.hpp>
class MyClass {
public:
MyClass(int i);
MyClass(const MyClass& myClass); // Copy-Constructor
void operator()() const; // entry point for the new thread
virtual void doSomething(); // Now you can use virtual functions
private:
int i; // and also fields very easily
};
MyClass clazz(1);
// Passing the object directly will create a copy internally
// Now you don't have to worry about the validity of the clazz object above
// after starting the other thread
// The operator() will be executed for the new thread.
boost::thread thread(clazz); // create the object on the stack
另一个 boost 示例在堆上创建线程对象,尽管这样做没有任何意义。
不隶属于 StackOverflow