Lucian Radu
Lucian Radu

Reputation: 105

How to continuosly run MPI programs?

I'm writing a C++ program using MPI to simulate traffic lights. Basically, I need that every two seconds, process 0 should send a message to all other processes (traffic lights) that they need to change colors. My current approach is something like (I don't have the actual code) :

if ( process_rank == 0)
{
   while(true)
   {
      Sleep(2000); //we sleep for 2 seconds

      for(i=1; i<=n;i++)
      {
         MPI_Send( message to change color to process i);
      }
   }
}
else
{
    MPI_Recv(message to change color);
}

The code is ok, no compilation errors, but the problem seems to be in my logic. For some reason I cannot understand, the program doen't do what expected. Is there a good way to continuosly run a MPI program and to send a message every X seconds? thank you

Upvotes: 0

Views: 236

Answers (1)

Your higher processes exit after the receive. If they shouldn't, the receives must be also in a loop.

Also the other logic of the program must fit there. You will probably se some functions to do the other useful stuff. Even the complete code for the master and for others may be in distinct functions.

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


int main(argc,argv)
  int argc;
  char *argv[];{
  int color, rank, numtasks;
  MPI_Status status;

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

  if ( rank == 0)
  {
     color = 0;
     while(1)
     {
        sleep(2); //we sleep for 2 seconds

        for(int i=1; i<numtasks;i++)
        {
           color = (color + 1) % 3;
           MPI_Send((void*)&color, 1, MPI_INT, i, 0, MPI_COMM_WORLD);
        }
     }
  }
  else
  {
   while(1)
     {
      MPI_Recv((void*)&color, 1, MPI_INT, 0, 0, MPI_COMM_WORLD, &status);
      printf("rank %i color is %i\n",rank, color);
     }
  }

  MPI_Finalize();
}

Upvotes: 1

Related Questions