问题
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