生产者和消费者相关问题

将生产者和消费者问题深入理解、融会贯通。

1.书上课后练习P187-43

semaphore  offer=1,P1,P2,P3, sugar,water,orange;
int mutex = 1;
begin
process_offer(){
  while(offer == 0){
    P(mutex);
    P(offer);
    offer();
    if(offer(orange))
      P(orange);
      V(P1);
    else if(offer(sugar))
      P(sugar);
      V(P2);
    else (offer(water))
      P(water);
      V(P3);
    V(mutex);
}
process_P1(){
  while(offer(orange)){
    P(mutex);
    P(P1);
    V(orange);
    V(mutex)
    produce();  //生产橘子汁
    V(offer);
  }
}

process_P2(){
  while(offer(sugar)){
    P(mutex);
    P(P2);
    V(sugar);
    V(mutex)
    produce();  //生产橘子汁
    V(offer);
  }
}

process_P3(){
  while(offer(water)){
    P(mutex);
    P(P3);
    V(water);
    V(mutex)
    produce();  //生产橘子汁
    V(offer);
  }
}

 

2.IPO问题:有多个输入进程、多个处理进程和多个输出进程。输入进程把数据逐步输入到一个有M个单位缓冲区B1上,经处理进程处理之后放到有N个单位的缓冲区B2上,由输出进程进行输出。

(1)这个问题有哪些进程?进程之间有什么样的制约关系?

    答:输入进程、处理进程以及输出进程,进程间存在有同步和互斥的关系。

(2)用信号量及PV操作写出这些进程之间的同步算法。

int B1[],B2[];
int in = 0;
int out = 0;
semaphore M,N,O;

process_Input(){
   while(in < M){
    P(M);
    append to B1[in];
    in++;
    输入进程;
    V(N);
   }
}

process_Process(){
   while(in > 0 && out < N){
    P(N);
    remove from B1[in]
    in--;
    append to B2[out];
    out++;
       处理进程;
    V(M);
    V(O);
   }
}

process_Output(){
   while(out > 0){
    P(O);
    remove from B2[out];
    out--;
    输出进程;
   }
}

 

3.探索哲学家问题的正确解法。

posted @ 2019-05-10 11:59  MrHsj  阅读(116)  评论(0编辑  收藏  举报