我编写了一个非常简单的线程代码。由于我对此很陌生,所以我不知道所提到的错误。
class opca_hello
{
public:
void hello();
}
void opca_hello::hello()
{
printf ("hello \n");
}
int main(int argc, char **argv)
{
opca_hello opca;
pthread_t thread1, thread2;
pthread_create( &thread1, NULL, opca.hello, NULL);
pthread_join( thread1, NULL);
return 0;
}
错误:类型为“void(opca_hello ::)()”的参数与“void *(*)(void *)”
不匹配答案 0 :(得分:3)
对成员函数的C ++调用需要将指针与其余参数一起传递给它。
所以使用线程写这样的代码:
static void *start(void *a)
{
opca_hello *h = reinterpret_cast<opca_hello *>(a);
h->hello();
return 0;
}
pthread_create( &thread1, NULL, start, &opca);
PS:
如果需要将参数传递给方法,请执行以下操作(例如):
struct threadDetails { opca_hello * obj; int p; };
static void *start(void *a)
{
struct threadDetails *td = reinterpret_cast<struct threadDetails *>(a);
td->obj->hello(td->p);
delete td;
return 0;
}
然后:
struct threadDetails *td = new struct threadDetails;
td->obj = &opca;
td->p = 500;
pthread_create( &thread1, NULL, start, td);