MPI - producer and consumer

早过忘川 提交于 2020-01-06 05:41:05

问题


how to simply make an producer and consumer app. Producer make item, sends it to the consumer, while consumer waits until he has this item. He use it, item is gone and he sends request to create new one to the producer. And over a over again.

I have mode some MPI_send and MPI_recv combination, but it just go only once. Producer make one item, consumer consume one item and app is deadlocked. Should I use non blocking recieve and send?

int count=10;
if(myrank==0){     //server
 for(i=0;i<10;i++){
    MPI_Recv(&a,1,MPI_INT,1,99,MPI_COMM_WORLD,&status);
    if (a==0){
      a=produced(); //here it returns 1
      MPI_Send(&a,1,MPI_INT,1,99,MPI_COMM_WORLD);
    }
  }

}
else{//client
 for(i=0;i<10;i++){
    if(a==0){
       a=0;
       MPI_Send(&a,1,MPI_INT,0,99,MPI_COMM_WORLD);
    }else{
       MPI_Recv(&a,1,MPI_INT,0,99,MPI_COMM_WORLD,&status);
       a=consumed();
       n++;
    }
    if(n==count){
       MPI_Finalize();

    }

 } 

}

edit:

int produced(){
   sleep(1);
   printf("Produced item\n");
   return 1;

}

int consumed(){
   sleep(1);
   printf("Consumed item\n");
   return 0;

}

回答1:


You shouldn't need non-blocking io for this. The problem is that nothing changes the client state so it will never receive anything. Try:

else { //client
  a=0;
  for (i=0;i<10;i++) {
    MPI_Send(&a,1,MPI_INT,0,99,MPI_COMM_WORLD);
    do {
      MPI_Recv(&a,1,MPI_INT,0,99,MPI_COMM_WORLD,&status);
    } while (a != 1);
    a=consumed();
  }

  MPI_Finalize();
}

Note the while loop isn't really needed above but as you have checked the server received data, I assumed you would want to check the client data received.

Edit: Changed to reflect source code for consumed() and produced()



来源:https://stackoverflow.com/questions/5440922/mpi-producer-and-consumer

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!