Multithreading in C++

In this tutorial, we will learn about multithreading and how we can make use of multithreading in C++.

Threads in C++

A thread is a logical or basic unit of a process. Thread in C++ is created using std::thread and it doesn’t return a value whereas Tasks which is created using std::async returns a value. In both Tasks and Threads, we can use

  • Pointer to function
  • Functor
  • Lambda function

The syntax for creating threads in C++

pthread_create(IdThread, attribute, start_routine, arg)

IdThread: refers to the unique identity of the thread.

attribute: refers to an attribute object which can be used to set multiple attributes of threads. By default it is NULL.

start_routine: thread always executes once when it is created.

arg:  the single argument is passed to start-routine. it must be passed by reference else by default null is used.

To terminate the thread in C++ pthread_exit() function is used.

Multithreading in C++

So, multithreading is a condition where a single processing unit that is CPU allows multiple threads to execute concurrently. As multithreading is different from multiprocessing. Multithreading is more like multitasking. There are two ways of multitasking, one is process-based and the other is thread-based.

Process-Based Multitasking helps in maintaining concurrent execution of the program.

whereas Thread-based multitasking helps in handling concurrent execution of parts of the current program.

In C++ 11 we have a multithreading concept before that we make use of POSIX threads or p threads library in c, which results in serious portability issues.

Under thread class, we have std: thread which represents a single thread in C++.

Initializing thread in C++

#include <iostream>
#include <thread>  // include this for thread class to apply multithreading in C++
using namespace std;
void threadFunc()
{
  cout << "Multithreading in C++11" << endl;
}
int main()
{
  thread funcTest1(threadFunc); // passing the function to thread
}

In the above code, we may face some errors while executing. As once a thread started executing we need to wait for the executing thread to finish before we move for further action.

So, to do this to wait for a thread we use the std::thread::join() function. This function ensures us that until the *this current executing function finished its execution we need to wait till then.

Final code:

#include <iostream>
#include <thread>
#include <chrono>

void worker_functionA(void)
{
        int loop = 0;
        while(loop < 5)
        {
            // Sleep for 1.00 seconds
            std::this_thread::sleep_for(std::chrono::milliseconds(1000));
            std::cout << "Thread First:  " << loop << std::endl;
            loop++;
        }
}

void worker_functionB(void)
{
        int loop = 0;
        // Loop 5 times
        while(loop < 5)
        {
           // Sleep for 2.22 seconds
           std::this_thread::sleep_for(std::chrono::milliseconds(2222));
           std::cout << "Thread Second: " << loop << std::endl;
           loop++;
        }
}

int main()
{
   char ans;
   std::thread worker_threadA(worker_functionA);   // passing the function to thread
   std::thread worker_threadB(worker_functionB); 

   // Pause the main thread
   std::cout << "Press key finish" << std::endl;
   std::cin >> ans;
   worker_threadA.join();    // Wait for Thread First to finish
   worker_threadB.join();  
 
   return 1;
}

 

Hope you liked this tutorial.

Also Read: How to concatenate multiple vectors in C++

Leave a Reply

Your email address will not be published.