/******************************************************************************
Hello World example:
In this example the rank 0 of MPI::COMM_WORLD waits for messages from the
other ranks. When a message is received it is displayed (send to stdout).
Copyright 2003 (c) Critical Software SA
. http://www.criticalsoftware.com
. http://www.criticalsoftware.com/hpc
. csWMPI II@criticalsoftware.com
*****************************************************************************/
#include "Hello_World.h"
#include <stdio.h>
#include <mpi.h>
#define MESSAGELENGTH 128 /* The length of the messages that */
/* we are going to transmit */
#define TAG 100 /* The tag to use for the transmissions */
/******************************************************************************
Constructor
*****************************************************************************/
CHello_World::CHello_World(int argc, char * argv[])
{
/* Initialize csWMPI II II: */
MPI::Init(argc, argv);
/* Determine what the world looks like and our own position in it: */
m_nCommSize = MPI::COMM_WORLD.Get_size();
m_nCommRank = MPI::COMM_WORLD.Get_rank();
printf("I am rank %d of %d in MPI_COMM_WORLD\n", m_nCommRank, m_nCommSize);
}
/******************************************************************************
Destructor
*****************************************************************************/
CHello_World::~CHello_World()
{
}
/******************************************************************************
main
*****************************************************************************/
int main(int argc, char *argv[])
{
int nCounter;
char pchMessage[MESSAGELENGTH];
char pchNodeName[MPI_MAX_PROCESSOR_NAME];
int nNodeNameSize;
CHello_World* pcHelloWorld = new CHello_World(argc, argv);
/* If I am rank 0 I'll receive messages from the other ranks in */
/* MPI::COMM_WORLD and send them to stdout: */
if (pcHelloWorld->m_nCommRank == 0) {
for (nCounter = 1; nCounter < pcHelloWorld->m_nCommSize; nCounter++) {
/* Receive a message from a process: */
MPI::COMM_WORLD.Recv(pchMessage,
MESSAGELENGTH,
MPI::CHAR,
MPI::ANY_SOURCE,
TAG);
/* Display the received message: */
printf ("I received the following message: %s\n", pchMessage);
fflush(stdout);
}
} else /* I am NOT rank 0 */ {
/* Get my node name */
MPI_Get_processor_name(pchNodeName, &nNodeNameSize);
/* Compose my message: */
sprintf(pchMessage,
"Hello world from rank %d at %s",
pcHelloWorld->m_nCommRank,
pchNodeName);
/* Send it: */
MPI::COMM_WORLD.Send(pchMessage,
MESSAGELENGTH,
MPI::CHAR,
0,
TAG);
}
/* Flush the output so it's shown when using mpiexec */
fflush (stdout);
/* Finalize csWMPI II II: */
MPI::Finalize();
/* Pause rank 0 so that the output can be verified: */
if (pcHelloWorld->m_nCommRank == 0) {
printf("\nPress ENTER to exit...\n");
fflush (stdout);
getchar();
}
delete pcHelloWorld;
return 0;
}
|