[英]mem_fun fails, pthread and class ptr
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);
另一方面,如果您真的不需要手動使用pthreads,那么最好看一下Boost.Thread (一個不錯的C ++線程庫)。 在那里,您可以獲得線程,鎖,互斥對象等的類,並且可以以更加面向對象的方式進行多線程處理。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.