假设我有一堂课,例如
class c {
// ...
void *print(void *){ cout << "Hello"; }
}
然后我有一个 c 向量
vector<c> classes; pthread_t t1;
classes.push_back(c());
classes.push_back(c());
现在,我想创建一个线程c.print();
以下给了我以下问题:
pthread_create(&t1, NULL, &c[0].print, NULL);
错误输出:无法将“void* (tree_item::*)(void*)”转换为“void*”
(*)(void*)’ 对于参数 ‘3’ 到 ‘int pthread_create(pthread_t*, const)
pthread_attr_t*, void* (*)(void*), void*)’
你不能按照你编写的方式来做,因为 C++ 类成员函数有一个隐藏的this
传入的参数。pthread_create()
不知道有什么价值this
使用,因此如果您尝试通过将方法转换为适当类型的函数指针来绕过编译器,您将遇到分段错误。您必须使用静态类方法(它没有this
参数),或者一个简单的普通函数来引导类:
class C
{
public:
void *hello(void)
{
std::cout << "Hello, world!" << std::endl;
return 0;
}
static void *hello_helper(void *context)
{
return ((C *)context)->hello();
}
};
...
C c;
pthread_t t;
pthread_create(&t, NULL, &C::hello_helper, &c);
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)