We perform thread.join() operation to join the child thread to the main thread. But think about a scenario, you have a large project, and you don’t know whether you have already joined the child thread to the main thread or not. So before joining the child thread to the main thread, we check if thread has already been joined or not.
We can understand it with below example:
using namespace std;
cout<<"This is function1 called by thread1"<<endl;
cout<<"This is function2 called by thread2"<<endl;
cout<<"Joining the Thread t1"<<endl;
cout<<"Joining the Thread t2"<<endl;
To run the code:
g++ -std=c++14 -pthread joinable.cpp
Output of the Code:
This is function2 called by thread2
This is function1 called by thread1
Joining the Thread t2
Lets understand the output of the code:
At lines number 17 and 18, we call function1 and function2. At line number 20, we join thread t1 to the main thread. When we again check if t1 is joinable or not using t1.joinable(), it returns false, thus we do not see output from the first if block. But when we check if t2.joinable() is true or not, it returns true because till this point we have not joined t2 to the main thread. Thus we enter the if block and can see the output from the second if block.
When std::thread::joinable() returns false:
- If the thread has already joined to the main thread or detached.
- If the thread has been moved elsewhere.