-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy path5a.c
49 lines (47 loc) · 1.26 KB
/
5a.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
#include "stdio.h"
#include "stdlib.h"
#include "mpi.h"
void my_bcast(void *data, int count, MPI_Datatype datatype, int root, MPI_Comm communicator)
{
int world_rank;
MPI_Comm_rank(communicator, &world_rank);
int world_size;
MPI_Comm_size(communicator, &world_size);
if (world_rank == root)
{
// If we are the root process, send our data to everyone
int i;
for (i = 0; i < world_size; i++)
{
if (i != world_rank)
{
MPI_Send(data, count, datatype, i, 0, communicator);
}
}
}
else
{
// If we are a receiver process, receive the data from the root
MPI_Recv(data, count, datatype, root, 0, communicator, MPI_STATUS_IGNORE);
}
}
int main(int argc, char **argv)
{
MPI_Init(NULL, NULL);
int world_rank;
MPI_Comm_rank(MPI_COMM_WORLD, &world_rank);
int data;
if (world_rank == 0)
{
data = 101;
printf("Process 0 broadcasting data %d\n", data);
my_bcast(&data, 1, MPI_INT, 0, MPI_COMM_WORLD);
}
else
{
my_bcast(&data, 1, MPI_INT, 0, MPI_COMM_WORLD);
printf("Process %d received data %d from root process\n",
world_rank, data);
}
MPI_Finalize();
}