Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can the thead joinable-join have a race condition? how do you get around it?

Tags:

c++

stdthread

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?

like image 469
IdeaHat Avatar asked Apr 03 '14 16:04

IdeaHat


People also ask

What does it mean if a thread is joinable?

Thread::joinable is an in-built function in C++ std::thread. It is an observer function which means it observes a state and then returns the corresponding output and checks whether the thread object is joinable or not. A thread object is said to be joinable if it identifies/represent an active thread of execution.

Is thread joinable by default?

thread::joinable So a default constructed thread is not joinable. A thread that has finished executing code, but has not yet been joined is still considered an active thread of execution and is therefore joinable.


Video Answer


1 Answers

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.

like image 53
Mike Seymour Avatar answered Oct 16 '22 21:10

Mike Seymour