0

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?

3
  • 1
    If it did compile, your m_read_thread would be a dangling reference after a foo is constructed. Why do you have a thread& member instead of a thread? Commented Dec 21, 2016 at 19:18
  • 1
    Don't make m_read_thread a reference. Commented Dec 21, 2016 at 19:18
  • This isn't the problem, but volatile sig_atomic_t is crufty old C for coordinating between the main program and a signal handler. Use std::atomic<bool> instead. Commented Dec 21, 2016 at 20:02

1 Answer 1

3

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)) 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.