Multithreading in C++ with Examples

The C++ programming language gives a ton of benefits to its users. It has various useful and efficient features and functionalities. In C++, Multithreading is one of the most important and useful features. Even today, Multithreading is one of the most used features. Let us learn more about it.

What is Multithreading in C++?

Multithreading is more like multitasking. With the help of multitasking, you can run two or more programs on your computer concurrently. There are two ways of multitasking such as process-based and thread-based.

The process-based multitasking helps in maintaining the concurrent execution of programs. And thread-based multitasking helps in handling the concurrent execution of pieces of the same program.

The meaning of multithreading is that two or more threads running concurrently. And each thread is handling a different task. It allows you to perform many activities simultaneously. C++ does not provide any support for Multithreaded applications, it entirely relies upon the operating system.

Let’s take an example to understand it better.

When you login to your Facebook account or you go to the news feed then you can see live videos, you can comment or even like that video, everything occurs simultaneously.

What is a Thread?

A thread is a lightweight process. Each thread executes different parts of a program. And each thread shares memory and other system resources. All thread functions are declared in the <pthread.h> header file in linux.

In this tutorial, we are going to use POSIX to write multithreaded C++ programs.

POSIX threads provide API that are present on many UNIX-like operating systems such as OpenBSD, FreeBSD, GNU/Linux, MAC OS X etc.

Creating Threads in C++

You can create a thread using the pthread_create() funcion.
Syntax:-

pthread_create(Idthread, attr, start_routine, arg)

In the above,

  • Idthread:– It is a unique identifier for each thread.
  • attr:- It is an attribute object that may be used to set multiple thread attributes. You can also provide thread attribute objects or you can set NULL for default values.
  • start_routine:- The thread will execute once it is created.
  • arg:- It is passed to start_routine as a single argument. It must be passed by reference as a pointer of type void. If you don’t pass any argument then null is used.

Terminating Threads in C++

You can terminate any thread using the pthread_exit() function. Normally, the pthread_exit() routine is called after a thread has completed its work and it is not required to exist.

Example:- Creating threads in C++

#include <iostream>
#include <pthread.h>
using namespace std;

char* st = "Child thread";

void* fun(void *st)
{
  cout << "Created child thread: " << (char*)st;
}
int main()
{
  pthread_t t;    
  pthread_create(&t, NULL, &fun, (void*)st);
  cout << "Created Main thread!" << endl;
  pthread_join(t, NULL);
  exit(EXIT_SUCCESS);
  return 0;
}

Output:-

Created Main thread!
Created child thread: Child thread

Joining and Detaching threads in C++

You can also join or detach threads in C++.

join() function in C++

You have to use the join() function to join a thread. Main thread will terminate only after the termination of the child thread. Main thread waits for the child thread to complete execution.

Syntax:-

name_of_the_thread.join();

You can also check if a thread is joinable or not using the joinable() function. It returns bool value.

Syntax:-

name_of_the_thread.joinable();

detach() function in C++

You can detach a thread from the parent thread using the detach() function. In this, the main and child thread execute independently.

Example:- Using C++ join() function

#include <iostream>
#include <unistd.h>  
#include <pthread.h>
using namespace std;

string str;
void* fun(void*)
{
  sleep(1);   
  cout << "Created child thread " << str << endl;
}

int main()
{
  pthread_t t[4];
  cout << "TechVidvan Tutorial: C++ Multithreading!"<<endl<<endl;
  for(int i=0; i<4; i++)
  {
    	cout << "Created -> Thread T[" << i << "]!" << str << endl;
    	pthread_create(&t[i], NULL, &fun, NULL);
    	pthread_join(t[i], NULL);
}
exit(EXIT_SUCCESS);
return 0;
}

Output:-

TechVidvan Tutorial: C++ Multithreading!

Created -> Thread T[0]!
Created child thread
Created -> Thread T[1]!
Created child thread
Created -> Thread T[2]!
Created child thread
Created -> Thread T[3]!
Created child thread

Example:- Using C++ detach() function

#include <iostream>
#include <unistd.h>   
#include <pthread.h>
using namespace std;

string str;
void* fun(void*)
{
  sleep(1);  
  cout << "Created Child thread!" << str << endl;
}

int main()
{
  pthread_t t[4];
  for(int i=0; i<4; i++)
  {
    	cout << "Created -> Thread T[" << i << "]!" << str << endl;
    	pthread_create(&t[i], NULL, &fun, NULL);
    	pthread_detach(t[i]);
}
exit(EXIT_SUCCESS);
return 0;
}

Output:-

Created -> Thread T[0]!
Created -> Thread T[1]!
Created -> Thread T[2]!
Created -> Thread T[3]!

Passing arguments to threads in C++

You can pass multiple arguments to threads using a structure. You can pass any data type in a thread callback.
Example:-

#include <iostream>
#include <cstdlib>
#include <pthread.h>

using namespace std;

#define NUM_THREADS 3

struct data{
   int  thread_id;
   char *msg;
};

void *DisplayHi(void *thread_arg) {
   struct data *val;
   val = (struct data *) thread_arg;

   cout << "Thread ID : " << val->thread_id ;
   cout << " Message : " << val->msg << endl;

   pthread_exit(NULL);
}

int main () {
   pthread_t threads[NUM_THREADS];
   struct data td[NUM_THREADS];
   int rc;
   int i;

   for( i = 0; i < NUM_THREADS; i++ ) {
  	cout <<"Creating Thread: " << i << endl;
  	td[i].thread_id = i;
  	td[i].msg = "Just a friendly Message!";
  	rc = pthread_create(&threads[i], NULL, DisplayHi, (void *)&td[i]);
 	 
  	if (rc) {
     	cout << "Error:unable to create thread," << rc << endl;
     	exit(0);
  	}
   }
   pthread_exit(NULL);
} 

Output:-

Creating Thread: 0
Creating Thread: 1
Thread ID : 0 Message : Just a friendly Message!
Creating Thread: 2
Thread ID : 2 Message : Just a friendly Message!
Thread ID : 1 Message : Just a friendly Message!

Advantages of Multithreading in C++

  • On a multi CPU system, Multithreading performs faster.
  • Using this, you can reduce performance and concurrency.
  • It helps you to access multiple applications simultaneously.
  • It also helps in enabling a program to make best use of available CPU.

Summary

In this tutorial, we discussed what is thread and multithreading in C++  We also discussed how you can create and terminate a thread. Then we talked over the process of joining and detaching threads in C++. We discussed how you can pass arguments to threads.