Addition or Subtraction of matrices takes O(n^2) time without threads but using threads we don’t reduce the time complexity of the program we divide the task into core like if we have 4 core then divide the matrix into 4 part and each core take one part of the matrix and compute the operations and finally when each task is complete then all 4 thread join the main program and show final output. Note –This method only works when we have more than one CPU core if we have only one core the Don’t create the thread because we divide the task and perform on only one CPU so it is waste of time to dividing a task and then compute.
Examples:
Input : Matrix A: 3 7 3 6 9 2 0 3 0 2 1 7 2 2 7 9 Matrix B: 6 5 5 2 1 7 9 6 6 6 8 9 0 3 5 2 Output : Sum of Matrix A and B: 9 12 8 8 10 9 9 9 6 8 9 16 2 5 12 11 Subtraction of Matrix A and B: -3 2 -2 4 8 -5 -9 -3 -6 -4 -7 -2 2 -1 2 7
Code – It is advised to execute the program in Linux based system.
#include <pthread.h> #include <stdio.h> #include <stdlib.h> // Value depend on System core #define CORE 4 // Maximum matrix size #define MAX 4 // Maximum threads is equal to total core of system pthread_t thread [CORE * 2];
int mat_A[MAX][MAX], mat_B[MAX][MAX], sum[MAX][MAX],
sub[MAX][MAX];
// Addition of a Matrix void * addition( void * arg)
{ int i, j;
int core = ( int )arg;
// Each thread computes 1/4th of matrix addition
for (i = core * MAX / 4; i < (core + 1) * MAX / 4;
i++) {
for (j = 0; j < MAX; j++) {
// Compute Sum Row wise
sum[i][j] = mat_A[i][j] + mat_B[i][j];
}
}
} // Subtraction of a Matrix void * subtraction( void * arg)
{ int i, j;
int core = ( int )arg;
// Each thread computes 1/4th of matrix subtraction
for (i = core * MAX / 4; i < (core + 1) * MAX / 4;
i++) {
for (j = 0; j < MAX; j++) {
// Compute Subtract row wise
sub[i][j] = mat_A[i][j] - mat_B[i][j];
}
}
} // Driver Code int main()
{ int i, j, step = 0;
// Generating random values in mat_A and mat_B
for (i = 0; i < MAX; i++) {
for (j = 0; j < MAX; j++) {
mat_A[i][j] = rand () % 10;
mat_B[i][j] = rand () % 10;
}
}
// Displaying mat_A
printf ( "\nMatrix A:\n" );
for (i = 0; i < MAX; i++) {
for (j = 0; j < MAX; j++) {
printf ( "%d " , mat_A[i][j]);
}
printf ( "\n" );
}
// Displaying mat_B
printf ( "\nMatrix B:\n" );
for (i = 0; i < MAX; i++) {
for (j = 0; j < MAX; j++) {
printf ( "%d " , mat_B[i][j]);
}
printf ( "\n" );
}
// Creating threads equal
// to core size and compute matrix row
for (i = 0; i < CORE; i++) {
pthread_create(& thread [i], NULL, &addition,
( void *)step);
pthread_create(& thread [i + CORE], NULL,
&subtraction, ( void *)step);
step++;
}
// Waiting for join threads after compute
for (i = 0; i < CORE * 2; i++) {
pthread_join( thread [i], NULL);
}
// Display Addition of mat_A and mat_B
printf ( "\n Sum of Matrix A and B:\n" );
for (i = 0; i < MAX; i++) {
for (j = 0; j < MAX; j++) {
printf ( "%d " , sum[i][j]);
}
printf ( "\n" );
}
// Display Subtraction of mat_A and mat_B
printf ( "\n Subtraction of Matrix A and B:\n" );
for (i = 0; i < MAX; i++) {
for (j = 0; j < MAX; j++) {
printf ( "%d " , sub[i][j]);
}
printf ( "\n" );
}
return 0;
} |
// Program to find sum of array // using multi-threading #include <iostream> #include <thread> using namespace std;
// Size of Matrix const int MAX = 4;
// Maximum number of threads const int MAX_THREAD = 4;
// matAdd and matSub to store results int matAdd[MAX][MAX];
int matSub[MAX][MAX];
int step_add = 0, step_sub = 0;
// Function to print matrix in readable format void printMatrix( int mat[][MAX])
{ for ( int i = 0; i < MAX; i++) {
for ( int j = 0; j < MAX; j++) {
cout << mat[i][j] << " " ;
}
cout << endl;
}
cout << endl;
} // Function to perform matrix subtraction void Subtraction( int matA[][MAX], int matB[][MAX])
{ int index = step_sub++;
// Each thread computes 1/4th of matrix addition
int start = index * (MAX / 4);
int end = (index + 1) * (MAX / 4);
for ( int i = start; i < end; i++) {
for ( int j = 0; j < MAX; j++) {
matSub[i][j] = matA[i][j] - matB[i][j];
}
}
} // Function to perform matrix Addition void Addition( int matA[][MAX], int matB[][MAX])
{ int index = step_add++;
// Each thread computes 1/4th of matrix addition
int start = index * (MAX / 4);
int end = (index + 1) * (MAX / 4);
for ( int i = start; i < end; i++) {
for ( int j = 0; j < MAX; j++) {
matAdd[i][j] = matA[i][j] + matB[i][j];
}
}
} int main()
{ // matrix A used for muliplication
int matA[MAX][MAX] = { { 3, 7, 3, 6 },
{ 9, 2, 0, 3 },
{ 0, 2, 1, 7 },
{ 2, 2, 7, 9 } };
// matrix B used for multiplication
int matB[MAX][MAX] = { { 6, 5, 5, 2 },
{ 1, 7, 9, 6 },
{ 6, 6, 8, 9 },
{ 0, 3, 5, 2 } };
cout << "Matrix A:" << endl;
printMatrix(matA);
cout << "Matrix B:" << endl;
printMatrix(matB);
// Creating list of size MAX_THREAD
thread add_thread[MAX_THREAD];
thread sub_thread[MAX_THREAD];
// Creating MAX_THEAD number of threads
for ( int i = 0; i < MAX_THREAD; i++) {
add_thread[i] = thread (Addition, matA, matB);
sub_thread[i] = thread (Subtraction, matA, matB);
}
// Waiting for all threads to finish
for ( int i = 0; i < MAX_THREAD; i++) {
add_thread[i].join();
sub_thread[i].join();
}
// Printing the resultant matrices
cout << "Sum of Matrix A and B:" << endl;
printMatrix(matAdd);
cout << "Subtraction of Matrix A and B:" << endl;
printMatrix(matSub);
return 0;
} // This code is contributed by shivhack999 |
// Java code addition import java.util.concurrent.*;
public class MatrixAdditionSubtraction {
// Size of Matrix
final static int MAX = 4 ;
// matrix A used for muliplication
static int [][] matA = { { 3 , 7 , 3 , 6 }, { 9 , 2 , 0 , 3 }, { 0 , 2 , 1 , 7 }, { 2 , 2 , 7 , 9 } };
// matrix B used for multiplication
static int [][] matB = { { 6 , 5 , 5 , 2 }, { 1 , 7 , 9 , 6 }, { 6 , 6 , 8 , 9 }, { 0 , 3 , 5 , 2 } };
// matAdd and matSub to store results
static int [][] matAdd = new int [MAX][MAX];
static int [][] matSub = new int [MAX][MAX];
// Function to print matrix in readable format
static void printMatrix( int [][] mat) {
for ( int i = 0 ; i < MAX; i++) {
for ( int j = 0 ; j < MAX; j++) {
System.out.print(mat[i][j] + " " );
}
System.out.println();
}
System.out.println();
}
// Function to perform matrix subtraction
static void subtract( int i) {
// Each thread computes 1/4th of matrix addition
int start = i * (MAX / 4 );
int end = (i + 1 ) * (MAX / 4 );
for ( int j = start; j < end; j++) {
for ( int k = 0 ; k < MAX; k++) {
matSub[j][k] = matA[j][k] - matB[j][k];
}
}
}
// Function to perform matrix Addition
static void add( int i) {
// Each thread computes 1/4th of matrix addition
int start = i * (MAX / 4 );
int end = (i + 1 ) * (MAX / 4 );
for ( int j = start; j < end; j++) {
for ( int k = 0 ; k < MAX; k++) {
matAdd[j][k] = matA[j][k] + matB[j][k];
}
}
}
public static void main(String[] args) {
System.out.println( "Matrix A:" );
printMatrix(matA);
System.out.println( "Matrix B:" );
printMatrix(matB);
// Creating MAX_THEAD number of threads
ExecutorService executor = Executors.newFixedThreadPool( 4 );
for ( int i = 0 ; i < 4 ; i++) {
int finalI = i;
executor.submit(() -> {
subtract(finalI);
add(finalI);
});
}
// Waiting for all threads to finish
executor.shutdown();
while (!executor.isTerminated()) {
// wait for all threads to complete
}
// Printing the resultant matrices
System.out.println( "Sum of Matrix A and B:" );
printMatrix(matAdd);
System.out.println( "Subtraction of Matrix A and B:" );
printMatrix(matSub);
}
} // The code is contributed by Nidhi goel. |
# Python3 Program to find sum of array # using multi-threading from threading import Thread
# Size of Matrix MAX = 4
# Maximum number of threads MAX_THREAD = 4
# matAdd and matSub to store results matAdd = [[ 0 for i in range ( MAX )] for j in range ( MAX )]
matSub = [[ 0 for i in range ( MAX )] for j in range ( MAX )]
step_add, step_sub = 0 , 0
# Function to print matrix in readable format def printMatrix(mat):
for row in mat:
print (row)
print ()
# Function to perform matrix subtraction def Subtraction():
global step_sub
index = step_sub
step_sub + = 1
# Each thread computes 1/4th of matrix addition
start, end = int (index * ( MAX / 4 )), int ((index + 1 ) * ( MAX / 4 ))
for i in range (start, end):
for j in range ( 0 , MAX ):
matSub[i][j] = matA[i][j] - matB[i][j]
# Function to perform matrix Addition def Addition():
global step_add
index = step_add
step_add + = 1
# Each thread computes 1/4th of matrix addition
start, end = int (index * ( MAX / 4 )), int ((index + 1 ) * ( MAX / 4 ))
for i in range (start, end):
for j in range ( 0 , MAX ):
matAdd[i][j] = matA[i][j] + matB[i][j]
if __name__ = = "__main__" :
# matrix A used for muliplication
matA = [[ 3 , 7 , 3 , 6 ],
[ 9 , 2 , 0 , 3 ],
[ 0 , 2 , 1 , 7 ],
[ 2 , 2 , 7 , 9 ]]
# matrix B used for multiplication
matB = [[ 6 , 5 , 5 , 2 ],
[ 1 , 7 , 9 , 6 ],
[ 6 , 6 , 8 , 9 ],
[ 0 , 3 , 5 , 2 ]]
print ( "Matrix A:" )
printMatrix(matA)
print ( "Matrix B:" )
printMatrix(matB)
# Creating list of size MAX_THREAD
add_thread = list ( range (MAX_THREAD))
sub_thread = list ( range (MAX_THREAD))
# Creating MAX_THEAD number of threads
for i in range (MAX_THREAD):
add_thread[i] = Thread(target = Addition)
add_thread[i].start()
sub_thread[i] = Thread(target = Subtraction)
sub_thread[i].start()
# Waiting for all threads to finish
for i in range (MAX_THREAD):
add_thread[i].join()
sub_thread[i].join()
# Printing the resultant matrices
print ( "Sum of Matrix A and B:" )
printMatrix(matAdd)
print ( "Subtraction of Matrix A and B" )
printMatrix(matSub)
|
// C# Program to find sum of array // using multi-threading using System;
using System.Threading.Tasks;
class MatrixAdditionSubtraction
{ // Size of Matrix
const int MAX = 4;
static int [,] matA = new int [MAX, MAX] { { 3, 7, 3, 6 }, { 9, 2, 0, 3 }, { 0, 2, 1, 7 }, { 2, 2, 7, 9 } };
static int [,] matB = new int [MAX, MAX] { { 6, 5, 5, 2 }, { 1, 7, 9, 6 }, { 6, 6, 8, 9 }, { 0, 3, 5, 2 } };
static int [,] matAdd = new int [MAX, MAX];
static int [,] matSub = new int [MAX, MAX];
// Function to print matrix in readable format
static void PrintMatrix( int [,] mat)
{
for ( int i = 0; i < MAX; i++)
{
for ( int j = 0; j < MAX; j++)
{
Console.Write(mat[i, j] + " " );
}
Console.WriteLine();
}
Console.WriteLine();
}
// Function to perform matrix subtraction
static void Subtract( int i)
{
// Each thread computes 1/4th of matrix addition
int start = i * (MAX / 4);
int end = (i + 1) * (MAX / 4);
for ( int j = start; j < end; j++)
{
for ( int k = 0; k < MAX; k++)
{
matSub[j, k] = matA[j, k] - matB[j, k];
}
}
}
static void Add( int i)
{
int start = i * (MAX / 4);
int end = (i + 1) * (MAX / 4);
for ( int j = start; j < end; j++)
{
for ( int k = 0; k < MAX; k++)
{
matAdd[j, k] = matA[j, k] + matB[j, k];
}
}
}
//Derive code
static void Main( string [] args)
{
Console.WriteLine( "Matrix A:" );
PrintMatrix(matA);
Console.WriteLine( "Matrix B:" );
PrintMatrix(matB);
Parallel.For(0, 4, i =>
{
Subtract(i);
Add(i);
});
Console.WriteLine( "Sum of Matrix A and B:" );
PrintMatrix(matAdd);
Console.WriteLine( "Subtraction of Matrix A and B:" );
PrintMatrix(matSub);
}
} // This code is contributed by shivhack999 |
Matrix A: [3, 7, 3, 6] [9, 2, 0, 3] [0, 2, 1, 7] [2, 2, 7, 9] Matrix B: [6, 5, 5, 2] [1, 7, 9, 6] [6, 6, 8, 9] [0, 3, 5, 2] Sum of Matrix A and B: [9, 12, 8, 8] [10, 9, 9, 9] [6, 8, 9, 16] [2, 5, 12, 11] Subtraction of Matrix A and B [-3, 2, -2, 4] [8, -5, -9, -3] [-6, -4, -7, -2] [2, -1, 2, 7]