【问题标题】:pthread_create - invalid use of non-static member function [duplicate]pthread_create - 无效使用非静态成员函数[重复]
【发布时间】:2016-07-06 12:53:48
【问题描述】:

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

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

send 函数还没有做任何事情,但它看起来是这样的。

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

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

【问题讨论】:

  • 非常简单,所有非成员函数都有一个隐藏的第一个参数,它成为this 变量。我建议您改为查看std::thread

标签: c++ pthreads


【解决方案1】:

如果您不能使用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);

【讨论】:

    猜你喜欢
    • 2011-01-27
    • 1970-01-01
    • 2017-05-19
    • 2019-05-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多