für das Splitten eines Kommunikators in zwei gleichstarke und die Kommunikation über einen Intercommunikator
#include "mpi.h"
#include <stdio.h>
#define NUMGROUPS 2
#define TAG 99
#define LEADER_EVEN 0 /* ids der Leader-Procs innerhalb des */
#define LEADER_ODD 1 /* Parent-Communicator MPI_COMM_WORLD */
#define ROOT 0
int main(int argc, char *argv[]) {
int me, newid, numprocs, groupsize, color, msg;
int local_leader, remote_leader;
MPI_Status stat;
MPI_Comm newcomm, intercomm;
if (MPI_Init(&argc, &argv)!=MPI_SUCCESS) {
fprintf(stderr,"MPI_Init failed.\n");
return -1;
}
MPI_Comm_rank(MPI_COMM_WORLD, &me);
MPI_Comm_size(MPI_COMM_WORLD, &numprocs);
color=me%NUMGROUPS;
if ((me==numprocs-1)&&(color!=1)) {
/* Die Prozeßgruppen sollen gleichstark sein */
color=MPI_UNDEFINED;
}
MPI_Comm_split(MPI_COMM_WORLD, color, me, &newcomm);
if (color!=MPI_UNDEFINED) {
MPI_Comm_rank(newcomm, &newid);
MPI_Comm_size(newcomm, &groupsize);
fprintf(stderr,"Proc %d: I'm now number %d in a group of %d.\n",
me, newid, groupsize);
MPI_Barrier(newcomm);
if (color==0) {
remote_leader=LEADER_ODD;
}
else {
remote_leader=LEADER_EVEN;
}
MPI_Intercomm_create(newcomm, ROOT, MPI_COMM_WORLD,
remote_leader, TAG, &intercomm);
if (color==0) {
msg=me;
/* msg an den Partnerprozeß in der anderen Gruppe */
MPI_Send(&msg,1,MPI_INT,newid,0,intercomm);
fprintf(stderr,"Proc %d: Sending %d to partner.\n", me, msg);
}
else {
MPI_Recv(&msg,1,MPI_INT,newid,MPI_ANY_TAG,intercomm,&stat);
fprintf(stderr,"Proc %d: Received %d from %d (tag %d)\n",
me, msg, stat.MPI_SOURCE, stat.MPI_TAG);
/* stat.MPI_SOURCE enthaelt die ID de Senders in */
/* dessen lokalen Kommunikator (newcom) */
}
MPI_Comm_free(&intercomm);
MPI_Comm_free(&newcomm);
}
else {
fprintf(stderr,"Proc %d: I'm in no group.\n", me);
}
MPI_Finalize();
}
| Makefile | C-Quelltext |