pthread_create - 无效使用非静态成员函数

pthread_create - invalid use of non-static member function

本文关键字:静态成员 函数 无效 create pthread      更新时间:2023-10-16

我一直在尝试学习如何使用线程,但我陷入了创建线程的困境。我正在这样的类构造函数中创建线程......

Beacon::Beacon() {
    pthread_create(&send_thread,NULL, send, NULL);
}

send 函数尚未执行任何操作,但如下所示。

void Beacon::send(void *arg){
    //Do stuff
}

每次我运行代码时,我都会收到无效使用非静态成员功能错误。我试过使用&发送,但没有用。我还为此设置了最后一个 NULL 参数,但这不起作用。我一直在查看其他示例代码来尝试模仿它,但似乎没有任何效果。我做错了什么?

如果你不能使用std::thread我建议你创建一个static成员函数来包装你的实际函数,并将this作为参数传递给函数。

类似的东西

class Beacon
{
    ...
    static void* send_wrapper(void* object)
    {
        reinterpret_cast<Beacon*>(object)->send();
        return 0;
    }
};

然后创建线程,例如

pthread_create(&send_thread, NULL, &Beacon::send_wrapper, this);