Maximum in a 2D matrix using Multi-threading in C++
Last Updated :
03 Feb, 2023
Given a 2-D matrix, find the element having maximum value using multi-threading.
Prerequisite : Multithreading
Examples :
Input : {{1, 5, 3, 6},
{22, 10, 4, 34},
{4, 45, 67, 3},
{69, 3, 23, 3}}
Output :69
Input :{{1, 2, 3}
{2, 4, 5}}
Output :5
A matrix can be of very large size so when it comes to traversing it, it will take lot of time. When finding the max element in a matrix, each element of the matrix is to be traversed which will take more time. So, to minimize the time taken in traversing the matrix can be avoided using multi-threading.
#include <bits/stdc++.h>
using namespace std;
pthread_t thread [2];
typedef struct dim
{
int s, e;
}dim;
int mat1[][4] = {{1, 5, 3, 6}, {22, 80, 4, 34},
{4, 45, 67, 3}, {99, 3, 23, 3}};
int maxf[2];
void *max( void *size)
{
int i, j, max;
dim *b = (dim *)size;
max = mat1[b -> s][0];
for (i = b -> s; i < b -> e; i++)
{
for (j = 0; j < 4; j++)
{
if (max < mat1[i][j])
max = mat1[i][j];
}
}
if (b -> s == 0)
maxf[0] = max;
else
maxf[1] = max;
}
int main()
{
int i, j;
dim *a, *b;
a = (dim *) malloc ( sizeof (dim));
b = (dim *) malloc ( sizeof (dim));
a -> s = 0; a -> e = 4/2;
pthread_create(& thread [0], NULL,
&max, ( void *)a);
b -> s = 4/2; b -> e = 4;
pthread_create(& thread [1], NULL,
&max, ( void *)b);
pthread_join( thread [0], NULL);
pthread_join( thread [1], NULL);
if (maxf[0] > maxf[1])
cout << maxf[0] << endl;
else
cout<< maxf[1] << endl;
return 0;
}
|
Output :
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...