C++中类的成员函数作为 pthread_create的线程函数

在C++的类中,普通成员函数作为pthread_create的线程函数就会出现参数问题,因为其不能作为pthread_create的线程函数,如果要作为pthread_create中的线程函数,必须是static !
为什么呢?
当把线程函数封装在类中,this指针会作为默认的参数被传进函数中,从而和线程函数参数(void*)不能匹配,不能通过编译。
但是当我把类中的作为pthread_create的线程函数改为static之后,又遇到新的问题?即在该方法中访问其他非静态方法或者是变量时,没法访问,关于这个问题又怎么解决呢?
答案:将this指针作为参数传递即可。

struct PthreadParams{
     Tree* pThis;
     /*
     *其它相应的参数 省略
     **/
}
class Tree {
 public :
 void splitPthread(TreeNode* node, const std::vector& data){
 /**
 相应程序业务处理 省略
 **/
pthread_t ThreadLeft,ThreadRgiht;  //定义线程
PthreadParams leftparams,rightparams;
//设置leftparams相应的参数 省略
pthread_create(&ThreadLeft,NULL,grow, (void*)leftparams);                   pthread_create(&ThreadRgiht,NULL,grow,(void*)rightparams);                  
pthread_join(ThreadLeft,NULL);
pthread_join(ThreadRgiht,NULL);
 }
static  void grow(void *p){
    PthreadParams *ptr = (PthreadParams*)p;
    //通过ptr->pThis;就可以访问类中非静态属性和方法 省略
}
}

你可能感兴趣的:(C++并行)