Linux pthread——有没有办法不把所有成员都创建为静态的?
linux pthread - is there a way not to create all the members as static?
我使用pthread创建线程(在c++应用程序中):
int result = pthread_create( &thread, NULL, CMyClass::RunThread, 0);
和CMyClass::RunThread必须是静态函数(为了被编译):
static void *RunThread(void *ptr);
所以从RunThread调用的所有类成员和辅助函数也必须是静态的。
似乎我有太多(~5)静态成员。(对我来说似乎不是一个好的程序…)
有更好的方法吗?更优雅的方式?
谢谢
- 将此指针传递给pthread_create
- 启动一个stub函数来解析这个
- 调用实际函数
伪代码如下:
// 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)处发生的事情。
相关文章:
- C++-我可以创建另一个类的成员并在构造函数中使用它吗
- int数据类型的指针指向的是什么,如果是一个类的私有数据成员,我们创建了该类的两个对象?
- 使用成员在类中创建 lambda 表达式
- 使用带有 ref 参数的成员函数创建线程时出现编译错误
- C++ 双向链表:使用矩阵类成员创建和填充列表
- C++:将向量传递到构造函数以创建成员变量的最佳方法?
- 从类指针的向量创建成员变量的向量
- 根据模板参数条件 C++17 创建成员别名
- 为原始指针、智能指针和值创建成员函数的编译时变体
- C :如何声明std ::函数而无需创建成员函数以分配给它们
- VS2017 非标准语法。使用 ' &' 创建成员指针
- 根据C 中的变量值创建成员函数
- 在C++中创建成员函数模板专用化
- 如果成员对象是父类的一部分,则无法创建成员对象
- 如何通过元编程正确创建成员模板函数指针数组
- 需要帮助创建c++成员函数来表示任务与RTOS microcos III
- 在可变模板函数中创建成员函数指针元组
- 如何在实例和静态作用域之间创建成员变量
- 将使用typedef创建成员吗?
- 内部类——c++,内部类,以及为什么你只能创建成员作为指向它们的指针