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

时间:2013-11-27 19:00:43

标签: c++ multithreading

我有以下代码,不能使用

进行编译
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);
                ^  ~~~~~~

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

2 个答案:

答案 0 :(得分:2)

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

#include <functional>

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

这提供了类实例。

答案 1 :(得分:1)

因为该函数是非静态的,所以线程没有类实例来调用该方法。为此,您可以创建一个静态函数,将您的调用转发给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();
}