Join in C++ Multithreading

From the line number 20 and 21 in the below code, if we remove t1.join() and t2.join(), our main thread will not wait for t1 and t2 to gets complete. So even before the execution of t1 and t2, main thread will terminate, and program execution will complete, so we will not be able to see the output of thread t1 and thread t2.

#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); //creation of thread1 and calling the function1
	std::thread t2(function2); //creation of thread2 and calling the function2

	t1.join(); //waiting for thread1 to execute
	t2.join(); //waiting for thread2 to execute

	return 0;
}
Command to Execute the code:
g++ -std=c++14 -pthread threadCreation.cpp
./a.out

You can try executing the above code by removing line number 20 and 21. You will not see the output from function1 and function2.

So why are we not able to see the output of function1 and function2? Let’s try to understand this.

At line number 18, we are having three threads in our system, one is the main thread, and the other two are t1 and t2. Main thread is the parent thread and t1, t2 are child threads. Child threads will be there in the system till the time parent thread is there in the system. So when t1 and t2 go for the function execution, parent thread i.e. main thread completes its execution and terminates. Now in the system, we are having only two threads t1, t2 and their parent thread i.e. main thread is not there in the system(it has completed its execution). So t1 and t2 also terminate without generating their output.


So if we use t1.join() and t2.join(), it means main thread is waiting for t1 and t2 to complete their execution and we see the output from function1 and function2.

Posted in C++