将线程作为C++类的成员启动的最佳方法是什么?

jdt*_*141 16 c++ pthreads

我想知道启动一个C++类成员的pthread 的最佳方法是什么?我自己的方法作为答案......

rav*_*int 23

这可以通过使用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
Run Code Online (Sandbox Code Playgroud)

笔记:

  • 这使用普通的类成员函数.无需添加额外的静态成员,这会使您的类接口混乱
  • 只需在启动线程的源文件中包含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
Run Code Online (Sandbox Code Playgroud)

  • 增强+1!不要挑剔,但你的变量`cMyClass theClass`实际上不应该被称为`cMyClass theObject`,因为它不是一个类而只是一个实例?我认为这会更清楚. (2认同)

shm*_*elp 15

我通常使用类的静态成员函数,并使用指向该类的指针作为void*参数.然后,该函数可以执行线程处理,或者使用类引用调用另一个非静态成员函数.然后,该函数可以引用所有类成员而不会出现笨拙的语法.


Ada*_*eld 11

你必须使用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);