forked from scottblechman/cs-4379-001-02
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.c
75 lines (64 loc) · 1.92 KB
/
main.c
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<stdio.h>
#include<stdlib.h> // rand(), srand()
#include<time.h>
#define RANKS 8
#define DEBUG
int main(int argc, char** argv) {
int ranks=RANKS;
int size; // needed for sending # of processes to MPI
int rank;
MPI_Init(&argc, &argv);
MPI_Comm_rank(MPI_COMM_WORLD, &rank);
MPI_Comm_size(MPI_COMM_WORLD, &size);
#ifdef DEBUG
//sleep a certain amount of s (offset based on ranks to demonstrate sync)
int offset = rank+1;
int s = 0;
for(int i = 0; i < 500000000*offset; i++){
s = i;
}
#endif
int data = 1;
MPI_Status status;
int step;
// BROADRECEIVE
for(step = ranks>>1; step >= 1; step = step >> 1) {
if(rank < step) {
#ifdef DEBUG
printf("%d:\t here0 %d\t Recv? = %d\t Tag = %d\n",
rank, step, rank+step, rank);
#endif
MPI_Recv(&data, 1, MPI_INT, rank+step, rank, MPI_COMM_WORLD, &status);
} else if (rank < 2*step) {
MPI_Send(&data, 1, MPI_INT, rank-step, rank-step, MPI_COMM_WORLD);
#ifdef DEBUG
printf("%d:\t here0 %d\t Send? = %d\t Tag = %d\n",
rank, step, rank-step, rank-step);
#endif
}
}
// BROADCAST
#ifdef DEBUG
printf("%d: Broadcast\n", rank);
#endif
for(step = 1; step < ranks; step = step << 1){
#ifdef DEBUG
printf("%d:\tStepBroadcast: %d\n", rank, step);
#endif
if(rank < step) {
MPI_Send(&data, 1, MPI_INT, rank+step, rank+step, MPI_COMM_WORLD);
#ifdef DEBUG
printf("%d:\t here1 %d\t Send = %d\t Tag = %d\n",
rank, step, rank+step, rank+step);
#endif
} else if(rank < 2*step) {
MPI_Recv(&data, 1, MPI_INT, rank-step, rank, MPI_COMM_WORLD, &status);
#ifdef DEBUG
printf("%d:\t here1 %d\t Recv = %d\t Tag = %d\n",
rank, step, rank-step, rank);
#endif
}
}
return MPI_Finalize();
}