当前位置:  开发笔记 > 编程语言 > 正文

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

如何解决《将线程作为C++类的成员启动的最佳方法是什么?》经验,为你挑选了3个好方法。

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



1> ravenspoint..:

这可以通过使用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


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

2> shmuelp..:

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



3> Adam Rosenfi..:

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

推荐阅读
360691894_8a5c48
这个屌丝很懒,什么也没留下!
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有