POSIX 标准下,创建线程的pthread_create函数原型是:
int pthread_create(pthread_t *thread, pthread_attr_t *attr, void*(*start_routine)(void *), void *arg)
在 C 中,,只要定义一个参数和返回值均为 void * 类型的函数,使用函数名字作为参数即可。就算不完全符合,可以使用 (void *(*)(void *)) 将其强制转换为符合类型检查规格的函数指针。
但在C++中,类的非静态成员函数隐含 this 指针作为第一个参数,所以参数完全不可能转化为 void * 类型,如果使用函数名字作为参数传入第三个参数,实际传入的即为this(类名::),pthread_create()拿this可就一点办法都没有。。。解决思路是,将没有隐藏this指针的函数地址传入pthread_create(),同时,又保证this能够传入执行体。
点击打开链接
解决方法 :定义线程开始函数为类的静态成员函数(static member function),或者不属于类的返回值为void *的开始函数,这样就不隐含 this 指针了,然后将 this 指针从 pthread_create 最后一个参数传给开始函数,在函数中将 void * 类型的 this 指针强制转换为类指针。举例如下:
class c{...
void *print(void *){ cout << "Hello"; }
}
static void* execute_print(void* ctx) {
c* cptr = (c*)ctx;
cptr->print();
return NULL;
}
void func() {
...
pthread_create(&t1, NULL, execute_print, &c[0]);
...
}