Skip to content

Instantly share code, notes, and snippets.

@Mikle-Bond
Created May 12, 2016 23:00
Show Gist options
  • Save Mikle-Bond/32bc3a4ae3552a5e2615b4219c1a5aec to your computer and use it in GitHub Desktop.
Save Mikle-Bond/32bc3a4ae3552a5e2615b4219c1a5aec to your computer and use it in GitHub Desktop.
#include <mpi.h>
#include <stdio.h>
#include <stdlib.h>
#ifdef DEBUG
#define dbg printf ("R%d:I%d: ", rank, i);
#else
#define dbg if(0)
#endif /* DEBUG */
// compile with
// mpicc hw.c -o hw.out
//
// run with
// mpirun -np 4 hw.out
int tagit(int a, int b) {
return (a<<8)+b;
}
int main(int argc, char * argv[])
{
int numtasks, rank, tmp;
int i = 0;
MPI_Status stat;
MPI_Request handle;
// Initialize the parallel stuff
tmp = MPI_Init(&argc, &argv);
if (tmp != MPI_SUCCESS) {
printf("MPI Initialization faild!\n");
MPI_Abort(MPI_COMM_WORLD, tmp);
}
// Get the info about the parallel stuff
MPI_Comm_size(MPI_COMM_WORLD, &numtasks);
MPI_Comm_rank(MPI_COMM_WORLD, &rank);
dbg printf("[INFO] Hello from the %d / %d\n", rank, numtasks);
// Check the call accuracy and show the quick help
if (argc < 2 && rank == 0) {
printf("Usage: %s <n>\n"
"where:\n"
"<n> number of iterations\n",
argv[0]);
MPI_Barrier(MPI_COMM_WORLD);
MPI_Abort(MPI_COMM_WORLD, tmp);
}
// initialize parameters from the command line
const int msg_size = 2 + atoi(argv[1]);
// Prepare buffers
char * buff_in = (char*) malloc(msg_size);
char * buff_out = (char*) malloc(msg_size);
char * swap;
// Prepare useful values
int prev = (rank == 0 ? numtasks - 1 : rank - 1);
int next = (rank + 1) % numtasks;
int tag_recv = tagit(prev, rank);
int tag_send = tagit(rank, next);
// LET THE GAMES BEGIN
for (i = 0; i < msg_size; ++i) {
buff_in[i] = rank;
dbg printf("Data writed\n");
swap = buff_out; buff_out = buff_in; buff_in = swap;
dbg printf("Buffers prepared\n");
MPI_Isend(buff_out, msg_size, MPI_CHAR, next, tag_send, MPI_COMM_WORLD, &handle);
dbg printf("Outcoming buffer sended to %d with tag %02d\n", next, tag_send);
MPI_Irecv(buff_in, msg_size, MPI_CHAR, prev, tag_recv, MPI_COMM_WORLD, &handle);
dbg printf("Incoming buffer recived from %d with tag %02d\n", prev, tag_recv);
MPI_Wait(&handle, &stat);
dbg printf("Transaction completed\n");
}
// dumping the message
printf("%d : %d", rank, buff_in[0]);
for (i = 1; i < msg_size; ++i)
printf(" >> %d", buff_in[i]);
printf("\n");
MPI_Finalize();
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment