【问题标题】:error: reference to non-static member function must be called when using std::thread with function that takes in a pointer错误:当使用带有指针的函数的 std::thread 时,必须调用对非静态成员函数的引用
【发布时间】:2020-12-22 19:00:40
【问题描述】:

我只是想在我的程序中做一些多线程,我的一个函数被称为Setup,它的调用如下:Setup(renderer); 并声明为void Setup(SDL_Renderer *renderer);,但是当我尝试让线程运行时我收到错误的函数:error: reference to non-static member function must be called 在线:std::thread th1(Setup, renderer);。如何让另一个线程运行程序的那个功能?

【问题讨论】:

    标签: c++ multithreading sdl-2


    【解决方案1】:

    Setup 似乎是一个成员函数。如果是这样,调用它的一种简单方法是使用传递给 std::thread 的 lambda:

    std::thread th1([this, renderer](){ this->Setup(renderer); });
    

    当调用成员函数时,编译器需要知道调用函数的对象。如果你只是做std::thread(Setup, renderer),编译器无法知道调用Setup函数的对象实例。

    您需要以某种方式将该实例传递给线程 - 正如我所展示的那样,使用 lambda 是一种方法。 this 仅在您尝试使用 Setup 函数在对象的成员函数内构造线程时才有效。如果没有,这里有一个稍微不同的例子:

    // You have some class with a Setup function...
    class A { public: void Setup(SDL_Renderer* renderer); };
    
    // You have an instance of that class:
    A a_instance;
    
    // You have the argument to the function
    SDL_Renderer* renderer = /**/;
    
    // You want to create a thread that runs A::setup on a_instance
    std::thread th1([a = &a_instance, renderer]()
    {
        a->Setup(renderer);
    });
    

    【讨论】:

    • 好的,有几件事。示例中的this 是什么,是类名吗?函数Setup 的类和声明不是静态的,我不确定这些信息是否有用。另一件事是它给了我另一个奇怪的错误:undefined reference to symbol 'pthread_create@@GLIBC_2.2.5'
    • 当你在一个非静态成员函数(类中的一个函数)中时,this 总是指调用该函数的对象。线程是在某个对象的某个实例上调用的某个函数内部创建的——this 就是那个实例。我们将this 传递给lambda,以便线程可以在适当的对象上调用Setup 函数。对于未定义的引用 - 您可能需要链接到 pthread。
    • 如果我也在同一个类的函数中进行多线程处理,那能正常工作吗?
    • 好的,它已编译,但现在我的代码显示一个黑色矩形而不是一些文本?
    • 听起来是一个不同的问题,你必须解决。如果多线程在属于同一个类的函数内,是的将会或可以工作。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-01-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多