Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if std::thread is valid

I got a class object, which only needs in some cases to start a thread. In the destructor it would be convenient for me to know whenever or not there is/was a thread. The question is, how do I detected if a std::thread object is or was a valid thread.

class MyClass
{
public:
   ~MyClass()
    {
       // Attention pseudocode!!!!!
       if(mythread is a valid object)
           mythread.join();

       if(mythread was a valid object in its lifetime)
           Do some stuff
    }

    void DoSomeStuff()
    {
      // May or may not create a thread
    }
private:
   std::thread mythread;
};
like image 928
Martin Schlott Avatar asked Aug 13 '14 08:08

Martin Schlott


1 Answers

I believe you're looking for the joinable function:

~MyClass()
{
    if (t.joinable()) { t.join(); }
}
like image 120
Kerrek SB Avatar answered Sep 19 '22 09:09

Kerrek SB