helloworld.c

来自「C语言编写的并行计算柏松矩阵」· C语言 代码 · 共 71 行

C
71
字号
#include <mpi.h>
#include <stdio.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 */


int main(int argc, char** argv) 
{
int nCommSize;
int nCommRank;
int nCounter;
char pchMessage[MESSAGELENGTH];
char pchNodeName[MPI_MAX_PROCESSOR_NAME];
int nNodeNameSize;

/* Initialize WMPI II: */ 
MPI_Init(&argc, &argv);

/* Determine what the world looks like and our own position in it: */
MPI_Comm_size(MPI_COMM_WORLD, &nCommSize);
MPI_Comm_rank(MPI_COMM_WORLD, &nCommRank);
printf ("I am rank %d of %d in MPI_COMM_WORLD\n", nCommRank, nCommSize);

/* If I am rank 0 I'll receive messages from the other ranks in */
/* MPI_COMM_WORLD and send them to stdout: */
if (nCommRank == 0) {
for (nCounter = 1; nCounter < nCommSize; nCounter++) {
/* Receive a message from a process: */
MPI_Recv(pchMessage, 
MESSAGELENGTH, 
MPI_CHAR, 
MPI_ANY_SOURCE,
TAG, 
MPI_COMM_WORLD, 
MPI_STATUS_IGNORE);

/* Display the received message: */ 
printf ("I received the following message: %s\n", pchMessage);
}
} 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", 
nCommRank, 
pchNodeName);
/* Send it: */
MPI_Send(pchMessage, MESSAGELENGTH, MPI_CHAR, 0, TAG, MPI_COMM_WORLD);
}

/* Flush the output so it's shown when using mpiexec */
fflush (stdout);

/* Pause rank 0 so that the output can be verified: */
if (nCommRank == 0) {
printf("\nPress ENTER to exit...\n");
fflush (stdout);
getchar();
}

/* Finalize WMPI II: */
MPI_Finalize();
return 0;
}

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?