Skip to content

Instantly share code, notes, and snippets.

@Mikle-Bond
Created May 15, 2016 12:36
Show Gist options
  • Save Mikle-Bond/1375382909cc6161dc2440bcd198df2a to your computer and use it in GitHub Desktop.
Save Mikle-Bond/1375382909cc6161dc2440bcd198df2a to your computer and use it in GitHub Desktop.
#include <mpi.h>
#include <stdio.h>
#include <stdlib.h>
#ifdef DEBUG
#define dbg
#else
#define dbg if(0)
#endif /* DEBUG */
// compile with
// mpicc hw.c -o hw.out
//
// run with
// mpirun -np 4 hw.out
#define from_0_to_1 0x12
#define from_1_to_0 0x15
#define player_body_3(self, enemy, TAG1, TAG2) \
MPI_Recv(buff, msg_size, MPI_CHAR, enemy, TAG2, MPI_COMM_WORLD, &stat); \
dbg printf("Iteration: %d\tplayer %d, message recived, my commandor\n", i, self); \
MPI_Send(buff, msg_size, MPI_CHAR, enemy, TAG1, MPI_COMM_WORLD); \
dbg printf("Iteration: %d\tplayer %d, message sent, my commandor\n",i, self); \
/* player_body_3 */
#define player_body(self, enemy) \
player_body_3(self, enemy, tagit(self, enemy), tagit(enemy, self))
/* player_body */
#define tagit(id1, id2) \
from_##id1##_to_##id2
/* tagit */
int main(int argc, char * argv[])
{
int numtasks, rank, res;
int i = 0;
MPI_Status stat;
// Initialize the parallel stuff
res = MPI_Init(&argc, &argv);
if (res != MPI_SUCCESS) {
printf("MPI Initialization faild!\n");
MPI_Abort(MPI_COMM_WORLD, res);
}
// Get the info about the parallel stuff
MPI_Comm_size(MPI_COMM_WORLD, &numtasks);
MPI_Comm_rank(MPI_COMM_WORLD, &rank);
// Check the call accuracy and show the quick help
if (argc < 4 && rank == 0) {
printf("\
Usage: %s <n> <size> <mes>\n\
where:\n\
<h> number of messages between threads\n\
<size> size in bytes of the message\n\
<mes> message to send, needs to fit into the <size> of bytes\n\
",
argv[0]);
MPI_Abort(MPI_COMM_WORLD, res);
}
// initialize parameters from the command line
const char * message = argv[3];
const int game_num = atoi(argv[1]);
const int msg_size = atoi(argv[2]);
char * buff = (char*) malloc(msg_size);
// Zero player starts the game
if (rank == 0) {
for (i = 0; message[i] && i < msg_size; ++i)
buff[i] = message[i];
buff[i] = message[i];
MPI_Send(buff, msg_size, MPI_CHAR, 1, from_0_to_1, MPI_COMM_WORLD);
printf("player %d, game started, my commandor\n", 0);
}
// LET THE GAMES BEGIN
// umm... 'continue' will be more correct...
for (i = 0; i < game_num; ++i) {
if (rank == 0) {
player_body(0, 1);
} else if (rank == 1) {
player_body(1, 0);
} else if (i == 0) {
// just introduce the spectators once
printf("I am %d, and a am a spectator\n", rank);
}
}
// And zero player finishs the game
if (rank == 1) {
MPI_Recv(buff, msg_size, MPI_CHAR, 0, from_0_to_1, MPI_COMM_WORLD, &stat);
if (msg_size == 0) {
printf("player %d, game finished, my commandor, without message\n", 1);
} else {
printf("player %d, game finished, my commandor, got %s\n", 1, buff);
}
}
MPI_Finalize();
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment