MPI basic example doesn't work

2019-08-09 02:42发布

I am trying to understand what was meant by the example below:

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

int main(int argc, char *argv[]) {
  int numtasks, rank, dest, source, rc, count, tag = 1;
  char inmsg, outmsg = 'x';
  MPI_Status Stat;

  MPI_Init(&argc, &argv);
  MPI_Comm_size(MPI_COMM_WORLD, &numtasks);
  MPI_Comm_rank(MPI_COMM_WORLD, &rank);

  if (rank == 0) {
    dest = 1;
    source = 1;
    rc = MPI_Send(&outmsg, 1, MPI_CHAR, dest, tag, MPI_COMM_WORLD);
    rc = MPI_Recv(&inmsg, 1, MPI_CHAR, source, tag, MPI_COMM_WORLD, &Stat);
  } else if (rank == 1) {
    dest = 0;
    source = 0;
    rc = MPI_Recv(&inmsg, 1, MPI_CHAR, source, tag, MPI_COMM_WORLD, &Stat);
    rc = MPI_Send(&outmsg, 1, MPI_CHAR, dest, tag, MPI_COMM_WORLD);
  }

  rc = MPI_Get_count(&Stat, MPI_CHAR, &count);
  printf("Task %d: Received %d char(s) from task %d with tag %d \n",
         rank, count, Stat.MPI_SOURCE, Stat.MPI_TAG);

  MPI_Finalize();
}

Essentially copied from here: https://computing.llnl.gov/tutorials/mpi/

Compiled like this:

$ mpicc -o ./mpi_test ./mpi_test.c

Run like this:

$ ./mpi_test 

Gives this error:

Fatal error in MPI_Send: Invalid rank, error stack:
MPI_Send(171): MPI_Send(buf=0x7fff787b4d93, count=1, MPI_CHAR, dest=1, tag=1, MPI_COMM_WORLD) failed
MPI_Send(97).: Invalid rank has value 1 but must be nonnegative and less than 1

To be honest, I don't understand why the example should have worked in the first place. Can you please enlighten me? Is the example wrong, or is the error expected? Perhaps my setup is wrong?

PS. Compiled with gcc 4.7 on Fedora 18 amd64

1条回答
Viruses.
2楼-- · 2019-08-09 03:07

You have to run your program using mpirun as follows:

mpirun -np 2 mpi_test
查看更多
登录 后发表回答