Thread Creation in C++


At the end of this tutorial, you will learn creating threads and how we can call the different functions using them.

So for a better understanding of the topic, we are going to take a simple example. We will create two threads t1, and t2. These two threads will call two functions, function1 and function2. Once the execution of both the threads is complete, they will be joined to the main thread. So below is the code for this scenario:

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

In main, at lines number 17 and 18, we are creating the two threads t1 and t2. Thread t1 is calling function1 and thread t2 is calling function2.
Once the execution of threads t1 and t2 are complete, both the threads are joined to the main thread.

When we run this code multiple times, we get different outputs. The reason for this is, both the threads t1 and t2 are created simultaneously. But due to the slight time difference in thread creation/execution, sometimes we see output from thread t2 first and then t1 and vice versa.

Note: Before moving ahead to the next tutorial, think about why are we using t1.join() and t2.join()?

Posted in C++