我已经为线程编写了一个非常简单的代码。由于我对此很陌生,所以我不知道提到的错误。
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*)”不匹配
最佳答案
C++ 对成员函数的调用需要传递指向 this 的指针以及其余参数。
所以要使用线程写这样的代码:
static void *start(void *a)
{
opca_hello *h = reinterpret_cast<opca_hello *>(a);
h->hello();
return 0;
}
pthread_create( &thread1, NULL, start, &opca);
附言:
如果您需要将参数传递给方法,请执行以下操作(例如):
结构线程细节{ opca_hello *obj; 诠释; };
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);
关于c++ - 错误 : argument of type "void (opca_hello::)()" does not match "void* (*)(void*)",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15331422/