user1876508
user1876508

Reputation: 13172

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

I have the following code, which does not compile using

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

and

#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;
}

I am given the following compiler errors, which seem a little ambiguous

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);
                ^  ~~~~~~

Is it legal to initialize a thread this way?

Upvotes: 0

Views: 2380

Answers (2)

chuck1
chuck1

Reputation: 675

Another method would be to use std::bind

#include <functional>

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

This provides the class instance.

Upvotes: 3

Raxvan
Raxvan

Reputation: 6505

because the function is non static the thread has no class instance to call that method on. To do this you can create a static function that will forward your call to your 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();
}

Upvotes: 1

Related Questions