0

我为线程编写了一个非常简单的代码。由于我对此很陌生,因此我不知道提到的错误。

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*)”不匹配

4

1 回答 1

3

对成员函数的 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);

PS:

如果您需要将参数传递给方法,请执行以下操作(例如):

struct threadDetails { opca_hello *obj; 诠释 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);
于 2013-03-11T05:09:33.560 回答