7

Lets say I have the following class

 class A
 {
 public:
    A()
    {
       my_thread=std::thread(std::bind(&A::foo, this));
    }
    ~A()
    {
       if (my_thread.joinable())
       {
          my_thread.join();
       }
    }
 private:
    std::thread my_thread;
    int foo();
 };

Basically, if my thread completes between the joinable and join calls, then my_thread.join will wait forever? How do you get around this?

IdeaHat
  • 7,641
  • 1
  • 22
  • 53

1 Answers1

13

Basically, if my thread completes between the joinable and join calls, then my_thread.join will wait forever?

No. A thread is still joinable after it has completed; it only becomes unjoinable once it has been joined or detached.

All threads must be joined or detached before the controlling thread object is destroyed.

Mike Seymour
  • 249,747
  • 28
  • 448
  • 644
  • 1
    Keeping in mind that thread objects can be moved (which changes which thread object is the controlling thread object). – James Kanze Apr 03 '14 at 16:38