-
Notifications
You must be signed in to change notification settings - Fork 182
/
skeleton.cpp
84 lines (64 loc) · 2.04 KB
/
skeleton.cpp
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
#include <cstdio>
#include <vector>
#include <mpi.h>
void init_buffers(std::vector<int> &sendbuffer, std::vector<int> &recvbuffer);
void print_buffers(std::vector<int> &buffer);
int main(int argc, char *argv[])
{
int ntasks, rank, size=12;
std::vector<int> sendbuf(size);
std::vector<int> recvbuf(size);
MPI_Status status;
MPI_Init(&argc, &argv);
MPI_Comm_size(MPI_COMM_WORLD, &ntasks);
MPI_Comm_rank(MPI_COMM_WORLD, &rank);
/* Initialize message buffers */
init_buffers(sendbuf, recvbuf);
/* Print data that will be sent */
print_buffers(sendbuf);
/* Send everywhere */
// TODO for broadcast: Implement the broadcast of the array sendbuf using send and recv functions
// TODO for scatter: Implement the scatter of the array sendbuf using send and recv functions
/* Print data that was received */
print_buffers(recvbuf);
MPI_Finalize();
return 0;
}
void init_buffers(std::vector<int> &sendbuffer, std::vector<int> &recvbuffer)
{
int rank;
int buffersize = sendbuffer.size();
MPI_Comm_rank(MPI_COMM_WORLD, &rank);
if (rank == 0) {
for (int i = 0; i < buffersize; i++) {
recvbuffer[i] = -1;
sendbuffer[i] = i;
}
} else {
for (int i = 0; i < buffersize; i++) {
recvbuffer[i] = -1;
sendbuffer[i] = -1;
}
}
}
void print_buffers(std::vector<int> &buffer)
{
int rank, ntasks;
int buffersize = buffer.size();
MPI_Comm_rank(MPI_COMM_WORLD, &rank);
MPI_Comm_size(MPI_COMM_WORLD, &ntasks);
std::vector<int> printbuffer(buffersize * ntasks);
MPI_Gather(buffer.data(), buffersize, MPI_INT,
printbuffer.data(), buffersize, MPI_INT,
0, MPI_COMM_WORLD);
if (rank == 0) {
for (int j = 0; j < ntasks; j++) {
printf("Task %2i:", j);
for (int i = 0; i < buffersize; i++) {
printf(" %2i", printbuffer[i + buffersize * j]);
}
printf("\n");
}
printf("\n");
}
}