LJ Archive

Listing 6. Telling Slaves to Quit

void master(long start, long stop, long nprocs){
  long work[2];
  long result;
  long total(0);
  long current(0);
  MPI_Status status;

  // dish out some work
  for (int rank=1; rank<nprocs; ++rank){
    // set the bounds for this work
    if (make_work(work,&current,stop))
      MPI_Send(work,2,MPI_LONG,
               rank,WORK,MPI_COMM_WORLD);
  }
  // keep sending work out while there is some
  while(make_work(work,&current,stop)){
    MPI_Recv(&result,1,MPI_LONG,MPI_ANY_SOURCE,
             MPI_ANY_TAG,MPI_COMM_WORLD,&status);
    total+=result;
    MPI_Send(work,2,MPI_LONG,status.MPI_SOURCE,
             WORK,MPI_COMM_WORLD);
  }
  // receive any outstanding requests
  for (int rank=1; rank<nprocs; ++rank){
    MPI_Recv(&result,1,MPI_LONG,MPI_ANY_SOURCE,
             MPI_ANY_TAG,MPI_COMM_WORLD,&status);
    total+=result;
  }
  // tell all salves to exit
  for (int rank=1; rank<nprocs; ++rank){
    MPI_Send(0,0,MPI_INT,rank,KILL,MPI_COMM_WORLD);
  }
  cout << "There were " << total;
  cout << " primes." << endl;
}
LJ Archive