微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

在生产者-消费者问题中访问缓冲区时是否必须使用互斥锁?

如何解决在生产者-消费者问题中访问缓冲区时是否必须使用互斥锁?

以下是由 galvin 等人给出的操作系统概念的生产者-消费者问题的伪代码。其他

我们假设池由 n 个缓冲区组成,每个缓冲区都能够容纳一个项目。 互斥二进制信号量为访问缓冲池提供互斥,并被初始化为值 1

 //initialization
 int n; 
 semaphore mutex = 1; 
 semaphore empty = n; 
 semaphore full = 0;

下面是生产者结构的伪代码

 while (true) 
{ 
   . . . 
  /* produce an item in next_produced */ 
  . . . 
  wait(empty); 
  wait(mutex); 
  . . . 
  /* add next produced to the buffer */ 
  . . . 
  signal(mutex); 
  signal(full); 
}

下面是消费者结构的伪代码

 while (true) 
 { 
   wait(full); 
   wait(mutex); 
   . . . 
   /* remove an item from buffer to next_consumed */ 
   . . . 
   signal(mutex); 
   signal(empty); 
   . . . 
   /* consume the item in next consumed */ 
   . . . 
}

以上就正文而言。让我更进一步,也包括缓冲区的工作。令 char buffer[n] 成为充当缓冲区的两个进程之间的共享数组。所以我们有:

/*Structure of the producer- elaborated by me*/
int i=0;
while (true) 
{ 
   . . . 
  /* produce an item in next_produced */ 
  . . . 
  wait(empty); 
  //wait(mutex); 
  . . . 
  buffer[i]=next_produced; 
  /* add next produced to the buffer */
  i=(i+1)%n; 
  . . . 
  //signal(mutex); 
  signal(full); 
}
/*Structure of the consumer elaborated by me*/
int i=0;
while (true) 
 { 
   wait(full); 
   //wait(mutex); 
   . . . 
   next_consumer=buffer[i]; 
   /* remove an item from buffer to next_consumed */ 
   i=(i+1)%n;
   . . . 
   //signal(mutex); 
   signal(empty); 
   . . . 
   /* consume the item in next_consumed */ 
   . . . 
}

虽然文本在访问缓冲区之前使用了互斥锁,(按照他们的逻辑,由于缓冲区是一个共享项,它应该以互斥的方式访问),但我认为使用互斥锁不是绝对必要的在访问缓冲区元素时,因为生产者和消费者虽然可以同时访问缓冲区,但我猜他们永远无法同时访问buffer数组的相同位置。由于它们不能同时访问同一个位置,因此不可能出现竞争条件...

这是我的感受。如果我错了,请纠正我。还请指出我犯错误的部分。谢谢。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。