In: Computer Science
Programming Language Required: C
Write a multithreaded program in C (not c++) using the pthread library and dynamic memory(malloc) that multiplies two matrices together. The numbers in the matrices must be read in from a text file. The program should also check if the two matrices are capable of being multiplied together. The amount of threads used has to be dynamic. The user should be able to choose how many threads they wish to use using the command line. Finally, the result must be stored in a text file.
1). ANSWER :
GIVENTHAT :
C - PROGRAM :
#include <bits/stdc++.h>
using namespace std;
int step_i = 0;
void* multi(void* arg)
{
int core = step_i++;
// Each thread computes 1/4th of matrix multiplication
for (int i = core * ma1 / 4; i < (core + 1) * ma1 / 4; i++)
for (int j = 0; j < mb1; j++)
for (int k = 0; k < mb2; k++)
matC[i][j] += matA[i][k] * matB[k][j];
}
// Driver Code
int main()
{
fstream file;
string word, filename;
filename = "example.txt";
file.open(filename.c_str());
cout<<"Enter dimensions of the first matrix :";
int ma1, ma2, mb1, mb2;
cin>>ma1>>ma2;
cout<<"Enter dimensions of the second matrix :";
cin>>mb1>>mb2;
int matA[ma1][ma2];
int matB[mb1][mb2];
if(ma2 != mb1)
{
cout<<"The matrices can't be multiplied.";
return 0;
}
int matC[ma1][mb2];
int MAX_THREAD = ma2;
for(int i = 0; i<ma1; i++)
{
for(int j = 0; j<ma2; j++)
{
file>>word;
matA[i][j] = word;
}
}
for(int i = 0; i<mb1; i++)
{
for(int j = 0; j<mb2; j++)
{
file>>word;
matB[i][j] = word;
}
}
// Displaying matA
cout << endl
<< "Matrix A" << endl;
for (int i = 0; i < ma1; i++) {
for (int j = 0; j < ma2; j++)
cout << matA[i][j] << " ";
cout << endl;
}
// Displaying matB
cout << endl
<< "Matrix B" << endl;
for (int i = 0; i < mb1; i++) {
for (int j = 0; j < mb2; j++)
cout << matB[i][j] << " ";
cout << endl;
}
// declaring four threads
pthread_t threads[MAX_THREAD];
// Creating four threads, each evaluating its own part
for (int i = 0; i < MAX_THREAD; i++) {
int* p;
pthread_create(&threads[i], NULL, multi, (void*)(p));
}
// joining and waiting for all threads to complete
for (int i = 0; i < MAX_THREAD; i++)
pthread_join(threads[i], NULL);
// Displaying the result matrix
cout << endl
<< "Multiplication of A and B" << endl;
for (int i = 0; i < ma1; i++) {
for (int j = 0; j < mb2; j++)
cout << matC[i][j] << " ";
cout << endl;
}
return 0;
}