MPI-生产者和消费者 [英] MPI - producer and consumer

查看:233
本文介绍了MPI-生产者和消费者的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何简单地制作生产者和消费者应用.生产者制造商品,将其发送给消费者,而消费者则等到他拥有该商品.他使用它,物品不见了,他向生产者发送创建新物品的请求.一遍又一遍.

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.

我有一些MPI_send和MPI_recv组合的模式,但是它只能运行一次.生产者生产一件商品,消费者消耗一件商品,而应用程序则陷入僵局.我应该使用非阻塞接收和发送吗?

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();

    }

 } 

}

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

}

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

}

推荐答案

为此,您不需要非阻塞io.问题是什么都不会改变客户端状态,因此它将永远不会收到任何东西.试试:

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();
}

请注意,上面实际上并不需要while循环,但是当您检查服务器接收到的数据时,我认为您将要检查接收到的客户端数据.

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.

编辑:已更改以反映consumed()produced()

这篇关于MPI-生产者和消费者的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆