joinable() in c++ Multithreading

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:

#include<iostream>
#include<thread>
using namespace std;

void function1()
{
	cout<<"This is function1 called by thread1"<<endl;
}

void function2()
{
	cout<<"This is function2 called by thread2"<<endl;
}

int main()
{
	std::thread t1(function1);
	std::thread t2(function2);

	t1.join();

	if(t1.joinable())
	{
		cout<<"Joining the Thread t1"<<endl;
		t1.join();
	}

	if(t2.joinable())
	{
		cout<<"Joining the Thread t2"<<endl;
		t2.join();
	}

	return 0;

}

To run the code:

g++ -std=c++14 -pthread joinable.cpp  
./a.out

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.

Posted in C++