include mpi include stdlib include time define MAIN_PROCESS void Broad

 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
#include <mpi.h>
#include <stdlib.h>
#include <time.h>
#define MAIN_PROCESS 0
void BroadcastArray(int *array, int arraySize, int blockSize, int currentProcRank, int procCnt) {
for (int process = 0; process < procCnt; ++process) {
int offset = process * blockSize;
if (offset < arraySize && process != currentProcRank) {
int sentElemsCnt = blockSize;
if (offset + blockSize > arraySize) {
sentElemsCnt = blockSize - (offset + blockSize - arraySize);
}
MPI_Send(array + offset, sentElemsCnt, MPI_INT, process, 0, MPI_COMM_WORLD);
}
}
}
void printArray(int *array, unsigned size) {
for (unsigned i = 0; i < size; ++i) {
printf(" [%d]: %d; ", i, array[i]);
}
}
int main (int argc, char** argv) {
srand((unsigned int) time(NULL));
int processRank, processesCnt;
int *array;
int rows = 3, cols = 3, arraySize = rows * cols;
MPI_Init (&argc, &argv);
MPI_Comm_rank (MPI_COMM_WORLD, &processRank);
MPI_Comm_size (MPI_COMM_WORLD, &processesCnt);
int blockSize = cols;
if (processRank == MAIN_PROCESS) {
array = new int[arraySize];
for (int i = 0; i < arraySize * arraySize; ++i) {
array[i] = rand() % 5;
}
printf("Created array: ");
printArray(array, arraySize);
for (int process = 1; process < processesCnt; process += 1) {
BroadcastArray(array, arraySize, blockSize, 0, processesCnt);
}
} else {
int offset = processRank * blockSize;
if (offset < arraySize) {
int receivedElemsCnt = blockSize;
if (offset + blockSize > arraySize) {
receivedElemsCnt = blockSize - (offset + blockSize - arraySize);
}
int *recvArray = new int[blockSize];
MPI_Status status;
MPI_Recv(recvArray, receivedElemsCnt, MPI_INT, MAIN_PROCESS, 0, MPI_COMM_WORLD, &status);
printf("\n Block recieved on %d process: \n", processRank);
printArray(recvArray, receivedElemsCnt);
int rowSum = 0;
for (int i = 0; i < cols; ++i) {
rowSum += recvArray[i];
}
if (abs(recvArray[processRank * cols + processRank]) > rowSum) {
printf("\n Diagonal is dominance on %d process \n", processRank);
}
}
}
}