类中不同成员函数的cpp中的pthread

pthread in cpp for different member functions in a class

本文关键字:cpp 中的 pthread 函数 成员      更新时间:2023-10-16

我从一个简单的例子开始http://www.tutorialspoint.com/cplusplus/cpp_multithreading.htm我需要将不同的cpp和标头划分为以下

Process_Images.h 中的类定义

void PrintHello(void* threadid);

在Process_Images.cpp 中

void ProcessImages::PrintHello(void* threadid)
{
   long tid;
   tid = (long)threadid;
   std::cout << "Hello World! Thread ID, " << tid << std::endl;
   pthread_exit(NULL);
}

在主要功能中

ProcessImages PI;
pthread_t threads[2];
pthread_create(&threads[0],NULL,PI.PrintHello,(void *)i);

错误为-->

/home/nvidia/Desktop/cms/tools/vibrante-vcm30t124-linux/cmsapplication_export/cmsapplication/sampleThread.cpp:333:69: error: cannot convert ���ProcessImages::PrintHello��� from type ���void (ProcessImages::)(void*)��� to type ���void* (*)(void*)���
      pthread_create(&threads[0],NULL,CarDetLEFT.PrintHello,(void *)i);
                                                                     ^

有什么建议吗?

因为我在问题中看到了C++11标签,所以绝对不需要经过pthread路由!

std::thread thr(&ProcessImages::PrinteHello, &PI, &i);

会对你有好处的!

两个问题:

  • 线程函数必须返回void*,而不是void
  • 线程函数不能是(非静态)成员函数

更多详细信息可在pthread_create的参考页面上找到。

因此,将ProcessImages::PrintHello的返回类型更改为void*,并使其成为static:

class ProcessImages {
  //<SNIP>
  public :
    static void* PrintHello(void* threadid);
  //<SNIP>
};

那么这应该会更好:

pthread_create(&threads[0], NULL, &ProcessImages::PrintHello, (void*) i);