C ++:使用pthread_create创建新线程,以运行类成员函数

时间:2012-08-28 13:20:41

标签: c++ multithreading pthreads

我有以下课程:

class A
{
    private:
        int starter()
        {
             //TO_DO: pthread_create()
        }

        void* threadStartRoutine( void *pThis );
}

我想从starter()内部创建一个线程来运行threadStartRoutine()。我得到关于第三个参数的编译时错误,它应该采用启动例程的地址。

调用pthread_create()创建一个开始执行threadStartRoutine()的新线程的正确方法是什么?

我在网上看到的文章说大多数编译器不允许使用pthread_create()调用非静态成员函数。这是真的?这背后的原因是什么?

我正在使用G ++在Linux-x64上编译我的程序。

4 个答案:

答案 0 :(得分:2)

threadStartRountine()声明为static

static void* threadStartRoutine( void *pThis );

否则,threadStartRoutine()的类型为:

void* (A::*)(void*)

这不是pthread_create()所需的函数指针类型。

答案 1 :(得分:2)

你有使用pthreads的理由吗? c ++ 11在这里,为什么不使用它:

#include <iostream>
#include <thread>

void doWork()
{
   while(true) 
   {
      // Do some work;
      sleep(1); // Rest
      std::cout << "hi from worker." << std::endl;
   }
}

int main(int, char**)
{

  std::thread worker(&doWork);
  std::cout << "hello from main thread, the worker thread is busy." << std::endl;
  worker.join();

  return 0;
}

答案 2 :(得分:2)

只需使用普通函数作为包装器。正如hjmd所说,静态函数可能是最好的正常函数。

答案 3 :(得分:0)

如果您坚持使用本机pthreads接口,则必须提供普通函数作为入口点。一个典型的例子:

class A
{
private:
    int starter()
    {
        pthread_t thr;
        int res = pthread_create(&thr, NULL, a_starter, this);
        // ...
    }
public:
    void run();
};

extern "C" void * a_starter(void * p)
{
    A * a = reinterpret_cast<A*>(p);
    a->run();
    return NULL;
}
相关问题