Feedback

C++ - MPI Beispiel 1

Veröffentlicht von am 6/16/2009
(1 Bewertungen)
Einfaches Beispiel, das die Verwendung von MPI (http://de.wikipedia.org/wiki/Message_Passing_Interface) zeigt.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>

//#include "mpi.h"
#include "../mpi_wrapper.h"

int master(MPI_Comm comm );
int slave( MPI_Comm comm );

int main( int argc, char** argv )
{
    int rank, size;
    MPI_Comm new_comm;

    mpi_Init( &argc, &argv );
    mpi_Comm_rank( MPI_COMM_WORLD, &rank );
    mpi_Comm_size( MPI_COMM_WORLD, &size );

	if (size<2)
	{
	  printf("Error: cannot execute with %d processors!\n", size);

	  mpi_Finalize ();
	  exit (EXIT_FAILURE);
	}

    mpi_Comm_split( MPI_COMM_WORLD, rank == 0, 0, &new_comm );

    if (rank == 0)
    	master( new_comm );
    else
    	slave( new_comm );

    MPI_Finalize( );
    return 0;
}

/* This is the master */
int master(MPI_Comm comm )
{
    int        i,j, size;
    char       buf[256];
    MPI_Status status;

    mpi_Comm_size( MPI_COMM_WORLD, &size );

    for (j=1; j<=2; j++)
    {
    	for (i=1; i<size; i++)
    	{
    		mpi_Recv( buf, 256, MPI_CHAR, i, 0, MPI_COMM_WORLD, &status );
    		fputs( buf, stdout );
    	}
    }

    return 0;
}

/* This is the slave */
int slave( MPI_Comm comm )
{
    char buf[256];
    int  rank;

    mpi_Comm_rank( comm, &rank );
    sprintf( buf, "Hello from slave %d\n", rank );
    mpi_Send( buf, strlen(buf) + 1, MPI_CHAR, 0, 0, MPI_COMM_WORLD );

    sprintf( buf, "Goodbye from slave %d\n", rank );
    mpi_Send( buf, strlen(buf) + 1, MPI_CHAR, 0, 0, MPI_COMM_WORLD );

    return 0;
}
Abgelegt unter MPI.

Kommentare zum Snippet

 

Logge dich ein, um hier zu kommentieren!