AppDividend
Latest Code Tutorials

Multithreading In C++ Example | C++ Multithreading Tutorial

0

Multithreading In C++ Example Tutorial is today’s topic. Multithreading is a type of model which at the time of execution allows multiple threads to exist within the context of the process such that they execute independently, but they share the process resource. A thread is the smallest sequence of programming instructions that can be managed by the scheduler. Running threads in parallel can increase the efficiency of programs.

Multithreading In C++

Multithreading is a technoscientific form of multitasking, and multitasking is a characteristic that allows the computer to run two or more programs simultaneously. Mainly, there are two types of multitasking:

1) process-based multitasking

2) thread-based multitasking.

Process-based multitasking controls the parallel execution of programs.

Thread-based multitasking deals with a concurrent execution of parts of the same program.

A multithreaded program contains two or more elements that can run concurrently. Each part of such a program is called the thread, and each thread defines a separate path of execution.

Multithreading support was introduced in C+11.  The std::thread is the thread class that describes a single thread in C++.

If we want to start a thread, we need to create the 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 the new thread.

#Multithreading in different systems

Multithreading in multicore and multiprocessor systems indicates that different threads are executed at the same time on different processors.

Multithreading in single-core systems divides the time between the different threads.

The operating system sends a certain number of instructions from different threads to the processor. Threads are not executed concurrently but in different time slots.

Operating System only exaggerates their simultaneous execution. This feature of an operating system is called multithreading.

#Syntax for creating a thread

It is essential to include the following header file.

#include<thread>

To create a thread, we have to create the object of the Thread class.

thread  thread_1;

#Example for creating and initializing a thread

See the following code file.

#include <iostream>
#include <thread>
using namespace std;

void threadFunction()
{
  cout << "Hello I am multithread How are you?" << endl;
}

int main()
{
  //pass a function to thread
  thread fun_1(threadFunction);
  fun_1.join();
  return (0);
}

See the output.

 

Multithreading In C++

Here in the output, we can see it shows an error. It’s because the main thread finishes before the fun_1 finishes.

If we want to remove the error, we can use the join() function as it will wait for all the running threads to complete before ending the main thread.

#Joining threads

Usually, we join two or more threads with join() function of the thread class.

The function only executes when all the threads except main thread are finished. It means that a main thread will wait until the child thread does not finish its execution.

Once the join() function returns anything, the threads become not joinable.

The thread is not joinable when it is default constructed or is moved/assigned to another thread or join() or detach() the member function is called.

To check if the thread is joined or not we use the joinable() function. It returns true if the function is joined and false if the function is not joined.

#Detaching threads

We use detach() function for detaching threads.

This function detaches the thread from a parent thread. It allows the parent and child threads to be executed independently from each other.

#Passing arguments to a thread

We can use the function with parameters for thread initialization. See the following code example.

void fun_1(int x, float y, char *z)
{
  cout << "The value of integer variable" << x << endl;
  cout << "The value of float variable" << y << endl;
  cout << "The char variable=" << z << endl;
}

The above function takes three arguments. If we want to initialize a thread with this function, first we have to pass the pointer to this function, then pass the parameters to the function in the same order as they are in the parameter list of a function. It can be done in the following way(continuing the above example).

char *z = "AppDividend";

  thread var_1(fun_1, 5, 4.2, z);
  if (var1.joinable())
    var_1.join();

Every thread has a unique identifier which is identified with the help of thread ID.

#Example Program of Multithreading in C++

See the following code.

#include <iostream>
#include <thread>
using namespace std;

void threadFunc()
{
  cout << "Hello I am multithread How are you?" << endl;
}

int main()
{
  //pass a function to thread
  thread funcTest1(threadFunc);
  funcTest1.detach();
  if (funcTest1.joinable())
  {
    //main is blocked until funcTest1 is not finished
    funcTest1.join();
  }
  else
  {
    cout << "The function is detached now" << endl;
  }
}

See the output.

 

Program of Multithreading in C++

#Create three threads and print a message from each thread in C++

See the following code.

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

using namespace std;

#define NUM_THREADS 5

void *Printmsg(void *thread_id)
{
  long t_id;
  t_id = (long)thread_id;
  cout << "I am a thread and my Thread ID is: " << t_id << endl;
  pthread_exit(NULL);
}

int main()
{
  pthread_t threads[NUM_THREADS];
  int k;
  int i;

  for (i = 0; i < NUM_THREADS; i++)
  {
    cout << "main() : creating thread, " << i << endl;
    k = pthread_create(&threads[i], NULL, Printmsg, (void *)i);

    if (k)
    {
      cout << "Error:unable to create thread," << k << endl;
      exit(-1);
    }
  }
  pthread_exit(NULL);
}

See the output.

 

C++ Multithreading Tutorial

Finally, Multithreading In C++ Example | C++ Multithreading Tutorial is over.

Leave A Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.