schrödinbug
schrödinbug

Reputation: 853

Run Member Function in Separate thread

I am trying to run a member function in its own thread and have followed this post, however in that example, the thread starts and finishes in the same function. How do you maintain a reference to the thread to join in a separate member function (say the destructor)? I have tried this:

class foo
{
    foo();
    ~foo();
    volatile sig_atomic_t m_run_thread = true;
    std::thread &m_read_thread;
    void read_thread();

}

foo::foo():m_read_thread(std::thread(&foo::read_thread, this))
{
}

foo::~foo()
{
     m_run_thread = false;
     m_read_thread.join();
}

void foo::read_thread()
{
    while(m_run_thread)
    {
    //do something cool
    }
}

int main()
{
   foo bar;
   //do other stuff
}

The compiler gives me an error though: error: invalid initialization of non-const reference of type ‘std::thread&’ from an rvalue of type ‘std::thread’. This is caused because I'm trying to bind a temporary to a reference. What's this best way to fix this?

Upvotes: 0

Views: 934

Answers (1)

NathanOliver
NathanOliver

Reputation: 180415

foo::foo():m_read_thread(std::thread(&foo::read_thread, this)) is not going to work as std::thread(&foo::read_thread, this) is a temporary value and a temporary cannot be bound to a non const lvalue reference.

That said there is no reason to make the thread member a reference. You can simple have a std::thread member like std::thread m_read_thread; and then in the constructor you would initialize it like

foo::foo() : m_read_thread(std::thread(&foo::read_thread, this))

Upvotes: 3

Related Questions