Multithreading C++ code



Multithreading in C++ - 

 
In Operating system, Multithreading provides the capability to process multiple threads at the same time by a CPU rather than processing multiple processes. 

Examples of Multithreading - 

  • Spelling checker and Grammar checker in Microsoft word at the same time

Below is c++ implementation of multithreading.

Here we are multiplying two matrices using multithreading - 

C++ code for Multithreading -


#include<stdio.h>
#include<unistd.h>
#include<stdlib.h>
#include<semaphore.h>
#include<sys/types.h>
#include<pthread.h>
#define pf printf
#define sf scanf
int m1[100][100],m2[100][100],i,j,k,res[100][100],r,c,sum;
void *input(void *arg)
{
pf("enter the size of matrix m1(row*col):\n");
sf("%d%d",&r,&c);
printf("enter the matrix elements:\n");
for(i=0;i<r;i++)
for(j=0;j<c;j++)
sf("%d",&m1[i][j]);
pf("enter the size of matrix m2(row*col):\n");
sf("%d%d",&r,&c);
printf("enter the matrix elements:\n");
for(i=0;i<r;i++)
for(j=0;j<c;j++)
sf("%d",&m2[i][j]);
}
void *multiplication(void *arg)
{
for(i=0;i<r;i++)
{
for(j=0;j<c;j++)
{
sum=0;
for(k=0;k<r;k++)
sum+=m1[i][k]*m2[k][j];
res[i][j]=sum;
}
}
}
void *print(void *arg)
{
pf("Resultant Matrix:\n");
for(i=0;i<r;i++)
{
for(j=0;j<c;j++)
pf("%d ",res[i][j]);
pf("\n");
}
}
int main()
{
pthread_t p[3];
pthread_create(&p[0],NULL,input,NULL);
sleep(15);
pthread_create(&p[1],NULL,multiplication,NULL);
pthread_create(&p[2],NULL,print,NULL);
pthread_join(p[0],NULL);
pthread_join(p[1],NULL);
pthread_join(p[2],NULL);
return 0;
}


Comments