-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmaster.c
More file actions
133 lines (91 loc) · 2.3 KB
/
master.c
File metadata and controls
133 lines (91 loc) · 2.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
#include <stdio.h>
#include <stdlib.h>
#include "mpi.h"
#include "config.h"
int *getMatrix(int m, int n) {
/*
returns a matrix of size m, n
*/
int *arr = (int*)malloc(sizeof(int)*m*n);
return arr;
}
int *getIdentityMatrix(int m) {
/*
returns an identity matrix of
size m, n
*/
int *I = getMatrix(m, m);
for(int i=0; i<m; i++) {
for(int j=0; j<m; j++) {
if (i == j)
I[i*m + j] = 1;
else
I[i*m + j] = 0;
}
}
return I;
}
int *Mastermatmul(int *result, int *A, MPI_Comm intercomm) {
/*
Broadcasts the matrix "result".
Scatters the matrix "A".
Gathers the matrix sent by each slave process.
*/
int *buf = getMatrix(M, M); // redundant for master.
int n_rows = M*M / P; // no. of rows to be sent to each child
MPI_Bcast(A, M*M, MPI_INT, MPI_ROOT, intercomm);
MPI_Scatter(result, n_rows, MPI_INT, buf, n_rows, MPI_INT, MPI_ROOT, intercomm);
MPI_Gather(&buf, n_rows, MPI_INT, result, n_rows, MPI_INT, MPI_ROOT, intercomm);
return result;
}
int main(int argc, char *argv[])
{
MPI_Comm intercomm;
int q = Q;
if (M % P != 0) {
perror("M (dimension of matrix) should be divisible by P (no. of slave processes spawned");
exit(0);
}
MPI_Init(&argc, &argv);
// spawning P no. of slave processes.
MPI_Comm_spawn("worker_program", MPI_ARGV_NULL, P, MPI_INFO_NULL, 0, MPI_COMM_SELF, &intercomm, MPI_ERRCODES_IGNORE);
// initialise result and A
int *result = getIdentityMatrix(M);
int *A = getMatrix(M, M);
printf("Enter a matrix of dimension %d x %d\n", M, M);
for(int i=0; i<M*M; i++)
scanf("%d", &A[i]);
printf("\nInput matrix:\n");
fflush(stdout);
for(int i=0; i<M; i++) {
for(int j=0; j<M; j++){
printf("%d ", A[i*M + j]);
fflush(stdout);
}
printf("\n");
fflush(stdout);
}
printf("\n");
fflush(stdout);
printf("Power to be calculated: %d\n\n", Q);
fflush(stdout);
while(q > 0) {
if (q % 2 == 1) {
result = Mastermatmul(result, A, intercomm);
}
A = Mastermatmul(A, A, intercomm);
q = q >> 1;
}
printf("Output matrix:\n");
fflush(stdout);
for(int i = 0; i < M; i++) {
for(int j = 0; j < M; j++) {
printf("%d ", result[i*M + j]);
fflush(stdout);
}
printf("\n");
fflush(stdout);
}
MPI_Finalize();
return 0;
}