你能初始化一个类中引用该类中函数的线程吗

Can you initialize a thread in a class which references a function inside that class?

本文关键字:引用 线程 函数 一个 初始化      更新时间:2023-10-16

我有以下代码,它不是使用编译的

clang++ -std=c++11 -pthread threaded_class.cpp -o test

#include <iostream>
#include <thread>
class Threaded_Class {
    public:
        Threaded_Class();
        void init();
};
Threaded_Class::Threaded_Class() {
    std::thread t1(init);
    t1.join();
}
void Threaded_Class::init() {
    std::cout << "Hello, world" << std::endl;
}
int main() {
    Threaded_Class a;
    return 0;
}

我收到了以下编译器错误,这些错误似乎有点模糊

threaded_class.cpp:13:20: error: reference to non-static member function must be
      called; did you mean to call it with no arguments?
    std::thread t1(init);
                   ^~~~
                       ()
threaded_class.cpp:13:17: error: no matching constructor for initialization of
      'std::thread'
    std::thread t1(init);
                ^  ~~~~~~

以这种方式初始化线程合法吗?

另一种方法是使用std::bind

#include <functional>
# instead of std::thread t1(init);
std::thread t1(std::bind(&Threaded_Class::init,this));

这提供了类实例。

因为函数是非静态的,所以线程没有类实例来调用该方法。为此,您可以创建一个静态函数,将您的调用转发到init:

class Threaded_Class {
public:
    Threaded_Class();
    void init();
    static void static_init(Threaded_Class * instance)
    {
        instance->init();
    }
};
Threaded_Class::Threaded_Class() {
    std::thread t1(static_init,this);//new line
    t1.join();
}