用信号量及其PV操作处理实际问题

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

1.书上课后练习P187-43

semaphore sugar,water,orange,S;

sugar=0;water=0;orange=0;S=1

process produce()

{

  while(true)

  {

    P(S)

    /*放入原料*/

    if 放入糖 than V(sugar)

    if 放入水 than V(water)

    if 放入橘子精 than V(orange)

  }

}

process P1()

{

  while(true)

  {

    P(orange)

    /*取出原料*/

    V(S)

    /*制作橘子汁*/

  }

}

process P2()

{

  while(true)

  {

    P(sugar)

    /*取出原料*/

    V(S)

    /*制作橘子汁*/

  }

}

process P3()

{

  while(true)

  {

    P(water)

    /*取出原料*/

    V(S)

    /*制作橘子汁*/

  }

}

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

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

    输入进程、处理进程、输出进程。进程之间为同步关系

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

semaphore b1full=0, b1empty=M, b2full=0, b2empty=N,mutex=1;

cobegin

process Input() {
while(true)
{
  P(b1empty);
  P(mutex);
  /*输入信息写入缓冲区B1*/
  V(mutex);
  V(b1full);
}

}

process P() {
while(true)
{
  P(b1full);

  P(mutex);

  /*从B1中取出信息;*/

  V(b1empty)

        /*加工信息;

         结果送去B2;*/

    P(b2empty);

  V(mutex)

  V(b2full)


}

}

process out() {

while(true)
{
  P(b2full);
  P(mutex);
  /*从B2中取出信息进行打印;*/
  V(mutex);
  V(b2empty);
}

}

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

posted @ 2019-05-09 19:31  白丶zt  阅读(173)  评论(0编辑  收藏  举报