MOdify the program below to do 3x3 matrix mutiplications: #include <iostream> #i
ID: 3691316 • Letter: M
Question
MOdify the program below to do 3x3 matrix mutiplications:
#include <iostream>
#include <cstdlib>
#include <pthread.h>
using namespace std;
int A[3] [3] = {{1,2},{3,4}};
int B[3] [3] = {{5,6},{7,8}};
int C[3] [3];
struct Position{
int row;
int col;
};
void *CalculateElement(void *pos){
Position *p = (Position *)pos;
C[p->row][p->col] = 0;
for(int i = 0; i < 3; i++){
C[p->row][p->col] += A[p->row][i]*B[i][p->col];
}
pthread_exit(NULL);
}
const int NUM_THREADS = 4;
int main()
{
pthread_t threads[NUM_THREADS];
for(int i = 0; i < NUM_THREADS; i++){
Position *p = new Position;
p->row = i/NUM_THREADS;
p->col = i%NUM_THREADS;
pthread_create(&threads[i], NULL, CalculateElement, (void *)p);
}
for(int i = 0; i < NUM_THREADS; i++){
pthread_join(threads[i], NULL);
}
cout << "The result matrix is: ";
for(int i = 0; i < 3; i++){
for(int j = 0; j < 3; j++){
cout << C[i][j] << " ";
}
cout << endl;
}
}
Explanation / Answer
Answer for Question:
I have updated the matrix A and B array values 3 x 3 .
Step 1: Update the A and B matrix values with 3 x 3 arrays.
int A[3] [3] = {{1,2,5},{3,4,6},{6,7,8}};
int B[3] [3] = {{5,6,9},{7,8,6},{3,5,8}};
Step 2: Updated Code:
#include <iostream>
#include <cstdlib>
#include <pthread.h>
using namespace std;
int A[3] [3] = {{1,2,5},{3,4,6},{6,7,8}};
int B[3] [3] = {{5,6,9},{7,8,6},{3,5,8}};
int C[3] [3];
struct Position
{
int row;
int col;
};
void *CalculateElement(void *pos){
Position *p = (Position *)pos;
C[p->row][p->col] = 0;
for(int i = 0; i < 3; i++){
C[p->row][p->col] += A[p->row][i]*B[i][p->col];
}
pthread_exit(NULL);
}
const int NUM_THREADS = 4;
int main()
{
pthread_t threads[NUM_THREADS];
for(int i = 0; i < NUM_THREADS; i++){
Position *p = new Position;
p->row = i/NUM_THREADS;
p->col = i%NUM_THREADS;
pthread_create(&threads[i], NULL, CalculateElement, (void *)p);
}
for(int i = 0; i < NUM_THREADS; i++){
pthread_join(threads[i], NULL);
}
cout << "The result matrix is: ";
for(int i = 0; i < 3; i++){
for(int j = 0; j < 3; j++){
cout << C[i][j] << " ";
}
cout << endl;
}
}
Step 3: Output
The result matrix is:
34 47 61
13 0 0
0 0 0
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.