8

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;
};
Praetorian
  • 106,671
  • 19
  • 240
  • 328
Martin Schlott
  • 4,369
  • 3
  • 25
  • 49

1 Answers1

10

I believe you're looking for the joinable function:

~MyClass()
{
    if (t.joinable()) { t.join(); }
}
Kerrek SB
  • 464,522
  • 92
  • 875
  • 1,084
  • 1
    Is it save to use t.joinable() on a threadobject which was never used? The documentation I found was a little bit unclear about that. – Martin Schlott Aug 13 '14 at 08:28