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?