# Addition and Subtraction of Matrix using pthreads in C/C++

CC++Server Side ProgrammingProgramming

#### C in Depth: The Complete C Programming Guide for Beginners

45 Lectures 4.5 hours

#### Practical C++: Learn C++ Basics Step by Step

Most Popular

50 Lectures 4.5 hours

#### Master C and Embedded C Programming- Learn as you go

66 Lectures 5.5 hours

Here we will see how to perform the matrix addition and subtraction using multithreaded environment. The pthread is used to execute multiple threads simultaneously in C or C++.

There are two matrices A and B. Order of each matrix is (m x n). Each thread will take each row, and perform addition or subtraction. So for m rows, there are m different threads.

## Example

#include<iostream>
#include <cstdlib>
#include <cstdint>
#define CORE 3
#define MAX 3
using namespace std;
int AMat[MAX][MAX] = {{10, 20, 30},
{40, 50, 60},
{70, 80, 50}
};
int BMat[MAX][MAX] = {{80, 60, 20},
{30, 20, 15},
{10, 14, 35}
};
void* addMatrices(void* arg) {
intptr_t core = (intptr_t)arg;
// Each thread computes 1/3rd of matrix addition
for (int i = core * MAX / 3; i < (core + 1) * MAX / 3; i++) {
for (int j = 0; j < MAX; j++) {
add[i][j] = AMat[i][j] + BMat[i][j];
}
}
}
void* subtraction(void* arg) {
intptr_t core = (intptr_t)arg;
// Each thread computes 1/3rd of matrix subtraction
for (int i = core * MAX / 3; i < (core + 1) * MAX / 3; i++) {
for (int j = 0; j < MAX; j++) {
sub[i][j] = AMat[i][j] - BMat[i][j];
}
}
}
void display(){
cout << "Matrix A: " << endl;
for(int i = 0; i < MAX; i++) {
for(int j = 0; j < MAX; j++) {
cout << AMat[i][j] << " ";
}
cout << endl;
}
cout << "\nMatrix B: " << endl;
for(int i = 0; i < MAX; i++) {
for(int j = 0; j < MAX; j++) {
cout << BMat[i][j] << " ";
}
cout << endl;
}
}
void displayRes(){
cout << "\nAddition: " << endl;
for(int i = 0; i < MAX; i++) {
for(int j = 0; j < MAX; j++) {
cout << add[i][j] << " ";
}
cout << endl;
}
cout << "\nSubtraction: " << endl;
for(int i = 0; i < MAX; i++) {
for(int j = 0; j < MAX; j++) {
cout << sub[i][j] << " ";
}
cout << endl;
}
}
main() {
display();
int step = 0;
for (int i = 0; i < CORE; i++) {
step++;
}
for (int i = 0; i < CORE * 2; i++) {
}
displayRes();
}

## Output

Matrix A:
10 20 30
40 50 60
70 80 50
Matrix B:
80 60 20
30 20 15
10 14 35
60 66 15