Newer
Older
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
#include<stdio.h>
#include<stdlib.h>
#include<mpi.h>
int main(int argc, char *argv[])
{
int i, myid, ntasks;
int size = 100000;
int *message;
int *receiveBuffer;
MPI_Status status;
MPI_Init(&argc, &argv);
MPI_Comm_size(MPI_COMM_WORLD, &ntasks);
MPI_Comm_rank(MPI_COMM_WORLD, &myid);
/* Allocate message */
message = malloc(sizeof(int) * size);
receiveBuffer = malloc(sizeof(int) * size);
/* Initialize message */
for (i = 0; i < size; i++) {
message[i] = myid;
}
/* Send and receive messages as defined in exercise */
if (myid == 0) {
MPI_Send(message, size, MPI_INT, 1, 1, MPI_COMM_WORLD);
MPI_Recv(receiveBuffer, size, MPI_INT, 1, 2, MPI_COMM_WORLD,
MPI_STATUS_IGNORE);
printf("Rank %i received %i\n", myid, receiveBuffer[0]);
} else if (myid == 1) {
/* One MPI tasks needs to start with send and the other one with
* receive, otherwise the program dead locks with large message
* sizes in most MPI implementations */
MPI_Recv(receiveBuffer, size, MPI_INT, 0, 1, MPI_COMM_WORLD,
MPI_STATUS_IGNORE);
MPI_Send(message, size, MPI_INT, 0, 2, MPI_COMM_WORLD);
printf("Rank %i received %i\n", myid, receiveBuffer[0]);
}
free(message);
free(receiveBuffer);
MPI_Finalize();
return 0;
}