Linux pthread——有没有办法不把所有成员都创建为静态的?

linux pthread - is there a way not to create all the members as static?

本文关键字:创建 成员 静态 有没有 pthread Linux      更新时间:2023-10-16

我使用pthread创建线程(在c++应用程序中):

int result = pthread_create( &thread, NULL, CMyClass::RunThread, 0);

和CMyClass::RunThread必须是静态函数(为了被编译):

static void *RunThread(void *ptr);

所以从RunThread调用的所有类成员和辅助函数也必须是静态的。

似乎我有太多(~5)静态成员。(对我来说似乎不是一个好的程序…)

有更好的方法吗?更优雅的方式?

谢谢

  1. 将此指针传递给pthread_create
  2. 启动一个stub函数来解析这个
  3. 调用实际函数

伪代码如下:

// static stub function
void* MyClass::thread_stub(void* p) {
  MyClass* c = static_cast<MyClass*>(p);
  return c->thread_func();
}
void* MyClass::thread_func() {
    return NULL;
}
int MyClass::start() {
    pthread_create(....thread_stub, this);
}

我经常这样做,因此,我创建了一个小模式来执行成员函数

#include <pthread.h>
#include <iostream>
template<class T, void*(T::*thread_func)(void*)>
class pthread_launcher {
public:
  pthread_launcher(T* obj=NULL, void* arg=NULL) : _obj(obj), _arg(arg) {}
  void *launch() { return (_obj->*thread_func)(_arg);}
private:
  /// Object pointer
  T* _obj;
  /// Command argument for member function
  void *_arg;
};
// Launch thread function
template<class T>
void *launch_member_function(void *obj)
{
  T* launcher = reinterpret_cast<T*>(obj);
  return launcher->launch();
}
typedef struct thread_arg {
  float fData;
} thread_arg_t;
class A {
 public:
  void* nonStaticFunction(void* arg) {
    std::cout << "Executing" << std::endl;
    return NULL;
  }
};
// (1)
template class pthread_launcher<A,&A::nonStaticFunction>;

int main() {
  thread_arg_t arg;
  arg.fData = 1.0f;
  // Laucher (2)
  pthread_launcher<A, &A::nonStaticFunction> launcher;
  // Initialize using function pointer and optional argument (2)
  launcher = pthread_launcher<A,&A::nonStaticFunction>(&a, &arg);
  A a;
  pthread_t thread;  
  // Start thread (4)
  pthread_create(&thread, NULL,
         launch_member_function<pthread_launcher<A,&A::nonStaticFunction> >,
         &launcher);
  pthread_join(thread,NULL);
  return 0;
}

你唯一需要一遍又一遍地做的是(1)(2)(3)和(4)处发生的事情。