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

C++: Creating new thread using pthread_create, to run a class member function

本文关键字:线程 运行 函数 成员 pthread 使用 create 新线程 创建 C++      更新时间:2023-10-16

我有以下类:

class A
{
    private:
        int starter()
        {
             //TO_DO: pthread_create()
        }
        void* threadStartRoutine( void *pThis );
}

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

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

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

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

threadStartRountine()声明为static:

static void* threadStartRoutine( void *pThis );

否则,threadStartRoutine()的类型为:

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

这不是CCD_ 4所需要的函数指针的类型。

使用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;
}

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

如果您坚持使用原生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;
}