多生产者-多消费者问题

semaphore mutex=1,apple=0,orange=0,plate=1;

dad(){
  while(true){
    准备一个苹果;
    P(plate);//表示自己要使用这个盘子
		P(mutex);
    把苹果放入盘子;
    V(mutex);
    V(apple);//盘子里苹果数量+1
  }
}

mom(){
  while(true){
    准备一个橘子;
    P(plate);//表示自己要使用这个盘子
		P(mutex);
    把橘子放入盘子;
    V(mutex);
    V(orange);//盘子里橘子+1
  }
}
daughter(){
  while(true){
    P(apple);//取出一个
    P(mutex);
    从盘中取苹果;
    V(mutex);
    V(plate);//空盘子+1
    吃苹果;
  }
}
son(){
  while(true){
    P(orange);
    P(mutex);
    从盘子取橘子;
		V(mutex);
    v(plate);
    吃橘子;
  }
}

上面的代码,因缓冲区plate的数量为1,因此可以省略掉mutex

但是如果plate大于1,就必须要使用mutex互斥信号量

考试的时候加上互斥信号一定不会错。就是要注意顺序,mutex的P操作必须在实现同步的P操作之后,否则可能引起死锁。

posted @ 2025-09-29 14:47  是我,米老鼠  阅读(12)  评论(0)    收藏  举报