Funktionsübersicht . . Blockierende Kommunikation . . Nichtblockierende Kommunikation

Hilfesystem für den Message Passing Interface Standard MPI


Beispiel für das asynchrone Empfangen von Nachrichten

#include "mpi.h"
#include <stdio.h>

#define DATA_SIZE 1000
#define ROOT      0
#define BUFLEN    1

int data[DATA_SIZE];
void init_data();
int  next_data(int dcount, int *buf);


int main(argc, argv) 
int        argc;
char       *argv[];
{
    int        numprocs, me, i, msglen, *buf;
    int        again=1, stop=-1, dcount=0;
    MPI_Status stat;

    if (MPI_Init(&argc,&argv)!=MPI_SUCCESS) {
	fprintf(stderr, "MPI_Init failed.");
	return -1;
    }
    MPI_Comm_size(MPI_COMM_WORLD, &numprocs);
    MPI_Comm_rank(MPI_COMM_WORLD, &me);
    if (me==ROOT) {
	init_data();
	buf=(int *)malloc(BUFLEN*sizeof(int));
	fprintf(stderr,"Next data <ENTER>\nType <q> to quit\n");
	i=1;
	while (1) {
            if (!(again=next_data(dcount, buf))) {
		break;
	    }
	    MPI_Send(buf,1,MPI_INT,i++,dcount++,MPI_COMM_WORLD);
	    if (i==numprocs) {
		i=1;
	    }
	}
	for (i=1; i<numprocs; i++) {
	    MPI_Send(&stop,1,MPI_INT,i,dcount++,MPI_COMM_WORLD);
	}
    }
    else {
	while (again) {
	    MPI_Probe(ROOT, MPI_ANY_TAG, MPI_COMM_WORLD, &stat);
	    MPI_Get_count(&stat, MPI_INT, &msglen);
	    buf=malloc(msglen*sizeof(int));
	    MPI_Recv(buf, msglen, MPI_INT, stat.MPI_SOURCE, stat.MPI_TAG, MPI_COMM_WORLD,
		     &stat);
	    if (buf[0]==stop) {
		again=0;
	    }
	    else {
	        fprintf(stderr,"Proc %d: Received data %d from %d with tag %d.\n",
		        me, buf[0], stat.MPI_SOURCE, stat.MPI_TAG);
	    }
	    free(buf);
	}
    }
    MPI_Finalize();
}

int next_data(int dcount, int *buf) {
    int    goon;
    int    again;

    again=(getchar()!='q');
    if (dcount>=DATA_SIZE-1) {
	again=0;
    }
    *buf=data[dcount];
    return again;
}

void init_data() {
    int  i;

    for (i=0; i<DATA_SIZE; i++) {
	data[i]=i+1;
    }
}

Makefile C-Quelltext