Multithreading in cpp || C++
In this, we are going to see a program on Multithreading in C++ Programming Language.



The Code given below can be used in gcc/g++ Compilers: -

#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);
}

#ENJOY CODING

Post a Comment

FOR ANY DOUBTS AND ERRORS FEEL FREE TO ASK. YOUR DOUBTS WILL BE ADDRESSED ASAP

Previous Post Next Post