Search code examples
c++c++11stdthread

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

Solution

  • I believe you're looking for the joinable function:

    ~MyClass()
    {
        if (t.joinable()) { t.join(); }
    }