Multithreading in C++

In this tutorial, we will learn about multithreading in C++.

Let’s first start with the basic ‘thread’. We can also say that a thread is the smallest unit of processing that can be performed in an OS. Now, Multithreading means two or more threads running concurrently where each thread is handling a different task.

Why do we need multithreading?

Multithreading environment allows you to run many activities simultaneously, where different threads are responsible for different activities. A real world example is social media. On most of the social media platforms, we have the ability to watch some video, hit a like, comment or share simultaneously. This is possible because of multiple threads running in the background and helping us to do multiple activities at the same time.

In the earlier versions of C++, we had to use pthreads library to achieve multithreading. However, with C++11, we have a prebuilt thread class that we can use. The syntax is :

#include <thread>
thread thread_object(callable)

To start a thread we simply create a new thread object and pass the executing code to be called (i.e, a callable object) into the constructor of the object. Once the object is created, a new thread is launched which executes the respective callable code.

Here is a simple program depicting the same :

Program to show Multithreading in C++

#include<iostream>
#include<thread>
using namespace std;
void func(int k)
{
  cout << "inside thread " << k << endl;
}
int main()
{
  cout << "Threads 1 and 2 and 3 operating independently" << endl;
  thread th1(func,1);
  thread th2(func,2);
  thread th3(func,3);
  th1.join();
  th2.join();
  th3.join();
  return 0;
}

Output:

Threads 1 and 2 and 3 operating independently
inside thread 1
inside thread 3
inside thread 2

Explanation:

In this program, I make three objects of thread type, passing to callable the function name and its parameter. Here, the parameter ‘int k’ is the number of thread that I make. That is, for the third thread I passed the value 3 to show the number of thread made is 3.

A callable, which we are passing in the constructor of the thread can be either of the following :

  • A function pointer
  • A function object
  • A lambda expression

The above example was of a function pointer. The general syntax of a function pointer is :

void function_name(parameters) 
{ 
         // function definition
} 

std::thread thread_obj(function_name, parameters);   // The parameters to the function are put after the comma

The syntax for a function object is :

// Define the class of function object 
class fn_object_class
 { 
    void operator()(parameters)    // Overload () operator 
   { 
       // function definition
    }
} 
std::thread thread_object(fn_class_object(), parameters)    // Create thread object 

The general syntax of a lambda expression is:

// Define a lamda expression 
auto f = [](parameters) { 
    // function definition 
}; 
std::thread thread_object(f, parameters);   // Pass f and its parameters to thread object constructor

or directly as

std::thread thread_object([](parameters) 
{ 
    // function definition
};, parameters);

Program:

#include<iostream>
#include<thread>
using namespace std;
class thread_obj		//define a function object
{
  public:
  void operator()(int x)
  {
    for (int i = 0; i < x; i++)
      cout << "Thread using function object as callable" << endl;
  }
};
int main()
{
  cout << "Threads 1 and 2 are operating independently" << endl;
  auto f = [](int x)		// Define a Lambda Expression 
  {
    for (int i = 0; i < x; i++)
      cout << "Thread using lambda expression as callable\n";
  };
  thread th1(thread_obj(), 3);		//thread with function obj as callable
  thread th2(f, 3);		//thread with lambda expression as callable
  th1.join();
  th2.join();
  return 0;
}

Output:

Threads 1 and 2 are operating independently
Thread using function object as callable
Thread using lambda expression as callable
Thread using lambda expression as callable
Thread using lambda expression as callable
Thread using function object as callable
Thread using function object as callable

Hope this was helpful. Enjoy Coding!

Also learn :

Mathematical Constants in C++

Read data from JSON file in C++

Leave a Reply

Your email address will not be published.