【问题标题】:C++: Creating new thread using pthread_create, to run a class member functionC++:使用 pthread_create 创建新线程,以运行类成员函数
【发布时间】:2012-08-28 13:20:40
【问题描述】:

我有以下课程:

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

        void* threadStartRoutine( void *pThis );
}

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

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

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

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

【问题讨论】:

标签: c++ multithreading pthreads


【解决方案1】:

threadStartRountine() 声明为static

static void* threadStartRoutine( void *pThis );

否则threadStartRoutine()的类型为:

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

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

【讨论】:

  • 我不能。该类是多线程的。将 threadStartRoutine 设为静态会导致我试图消除的内存泄漏错误。
  • @ShaileshTainwala,我不确定这两个参数中的任何一个如何阻止您创建函数static
  • “类是多线程的”这句话完全没有意义。这不是 C++ 和编程的工作方式。
  • @ShaileshTainwala:不要将函数设为静态。而是编写一个新的静态函数来调用你的静态函数,并将这个新函数用作pthread_create() 的参数。和大家开心!当然,您需要传递 this 参数,以便静态函数可以调用非静态函数。但这就是你有 pThis 参数的原因。
  • @ShaileshTainwala - 它们是函数,即。代码,带有堆栈参数,即。每个线程都不同。从多个线程调用静态函数,传递一个“this”指针,然后在“this”上调用一个方法是没有问题的。当涉及由所有调用者共享的静态数据时会出现问题。
【解决方案2】:

你有使用 pthread 的理由吗? 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;
}

【讨论】:

    【解决方案3】:

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

    【讨论】:

      【解决方案4】:

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

      【讨论】:

        猜你喜欢
        • 2016-10-22
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-04-27
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多