linux pthread - 有没有办法不将所有成员创建为静态?

时间:2015-07-19 16:52:49

标签: c++

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

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

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

static void *RunThread(void *ptr);

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

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

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

感谢

2 个答案:

答案 0 :(得分:0)

  1. 将此指针传递给pthread_create
  2. 启动解析此
  3. 的存根函数
  4. 称呼你的真实功能
  5. 伪代码如下所示:

    // 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);
    }
    

答案 1 :(得分:0)

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

#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)发生的事情。