Skip to content

Instantly share code, notes, and snippets.

@kaityo256
Last active October 18, 2022 03:35
Show Gist options
  • Save kaityo256/ac8b29168200b97a3e48b1b1afe0a26e to your computer and use it in GitHub Desktop.
Save kaityo256/ac8b29168200b97a3e48b1b1afe0a26e to your computer and use it in GitHub Desktop.
MPI_Probe sample
#include <mpi.h>
#include <cstdio>
#include <vector>
int main(int argv, char **argc){
MPI_Init(&argv, &argc);
int rank;
MPI_Comm_rank(MPI_COMM_WORLD, &rank);
int send_buf[] = {3,5,3,1,6,7,8,8};
int count = sizeof(send_buf)/sizeof(int);
if (rank==0){
printf("I will send %d data\n",count);
printf("Here are the data\n");
for(int i=0;i<count;i++){
printf("%d:%d\n",i, send_buf[i]);
}
MPI_Send(send_buf, count, MPI_INT, 1, 0, MPI_COMM_WORLD);
}
MPI_Barrier(MPI_COMM_WORLD);
if (rank==1){
MPI_Status st;
MPI_Probe(0, 0, MPI_COMM_WORLD, &st);
int size = st._ucount/sizeof(int);
printf("I will receive %d data from rank %d\n",size, st.MPI_SOURCE);
std::vector<int> recv_buf(size);
MPI_Recv(recv_buf.data(), size, MPI_INT, 0, 0, MPI_COMM_WORLD, &st);
printf("Here are the data.\n");
for(int i=0;i<size;i++){
printf("%d:%d\n",i, recv_buf[i]);
}
}
MPI_Finalize();
}
@kaityo256
Copy link
Author

$ mpic++ test.cpp
$ mpirun -np 2 ./a.out
I will send 8 data
Here are the data
0:3
1:5
2:3
3:1
4:6
5:7
6:8
7:8
I will receive 8 data from rank 0
Here are the data.
0:3
1:5
2:3
3:1
4:6
5:7
6:8
7:8

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment