c++ - 错误 : argument of type "void (opca_hello::)()" does not match "void* (*)(void*)"

标签 c++ linux pthreads

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

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/

相关文章:

c++ - 了解 C++ 中的继承

linux - 替换括号中的单词以放入引号中

c++ - VisualGDB c++ 到 RaPi Poco 没有这样的文件或目录

c++ - 在 C++ 中使用 pthreads 实现线程池

c - 使用 pthread_create 停止我的方法工作。为什么?使用 C

c++ - 如何在没有驱动程序的情况下使用 Qt5 打印 (PostScript/PCL)

c++ - RValue 引用在分配给另一个指针后是否删除它们的绑定(bind)(非指针)对象?

c++ - 编译时如何生成类似 OR 的语句? C++

linux - 如何找到文件中最低值的位置?

c++ - C++中的Pthread取消