Related Articles

# Maximum in a 2D matrix using Multi-threading in C++

• Difficulty Level : Hard
• Last Updated : 28 Mar, 2018

Given a 2-D matrix, find the element having maximum value using multi-threading.

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.

## Recommended: Please try your approach on {IDE} first, before moving on to the solution.

 `// CPP code to find max in 2d``// array using multi-threading``#include ``using` `namespace` `std;`` ` `// declaring two thread_id variable``pthread_t ``thread``;`` ` `// structure for passing arguments``typedef` `struct` `dim``{``    ``int` `s, e;``}dim;`` ` `// matrix of 4X4``int` `mat1[] = {{1, 5, 3, 6}, {22, 80, 4, 34},``            ``{4, 45, 67, 3}, {99, 3, 23, 3}};``int` `maxf;`` ` `// function that find max from a given array``void` `*max(``void` `*size)``{``    ``int` `i, j, max;``    ``dim *b = (dim *)size;``    ``max = mat1[b -> s];``     ` `    ``// finding max``    ``for``(i = b -> s; i < b -> e; i++)``    ``{``        ``for``(j = 0; j < 4; j++)``        ``{``            ``if``(max < mat1[i][j])``                ``max = mat1[i][j];``        ``}``    ``}``     ` `    ``// storing max from first half of``    ``// 2-d array into 0th index``    ``if``(b -> s == 0)``        ``maxf = max;``     ` `    ``// storing max from second half of``    ``// 2-d array into 1st index``    ``else``    ``maxf = max;``}`` ` `// driver function``int` `main()``{``    ``int` `i, j;``    ``dim *a, *b;``    ``a = (dim *)``malloc``(``sizeof``(dim));``    ``b = (dim *)``malloc``(``sizeof``(dim));``     ` `    ``// creating thread1``    ``a -> s = 0; a -> e = 4/2;``    ``pthread_create(&``thread``, NULL,``                ``&max, (``void` `*)a);``     ` `    ``b -> s = 4/2; b -> e = 4;``     ` `    ``// creating thr ead 2``    ``pthread_create(&``thread``, NULL,``                ``&max, (``void` `*)b);``     ` `    ``// waiting until the complition of threads``    ``pthread_join(``thread``, NULL);``    ``pthread_join(``thread``, NULL);``     ` `    ``// printing max``    ``if``(maxf > maxf)``    ``cout << maxf << endl;``    ``else``    ``cout<< maxf << endl;``     ` `    ``return` `0;``}`

Output :

``` ```
Want to learn from the best curated videos and practice problems, check out the C++ Foundation Course for Basic to Advanced C++ and C++ STL Course for foundation plus STL.  To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.

My Personal Notes arrow_drop_up