mem_fun失败,并行线程和类PTR
-
19-08-2019 - |
题
pthread
发生在作为其参数void *(*start_routine)(void* userPtr)
,我希望我可以使用std::mem_fun
解决我的问题,但我不能。
我想使用的功能void * threadFunc()
并具有userPtr
充当类(userPtr->threadFunc())
。是否有类似的功能,std::mem_func
,我可以使用?
解决方案
一种方法是使用一个全局函数来调用你的主线程功能:
class MyThreadClass {
public:
void main(); // Your real thread function
};
void thread_starter(void *arg) {
reinterpret_cast<MyThreadClass*>(arg)->main();
}
然后,当你要启动线程:
MyThreadClass *th = new MyThreadClass();
pthread_create(..., ..., &thread_starter, (void*)th);
在另一方面,如果你并不需要手动使用并行线程,它可能有一个看的 Boost.Thread 时,良好的C ++线程库。在那里,你得到类线程,锁,互斥等,并且可以在一个更面向对象的方法做多线程。
不隶属于 StackOverflow