问题描述
以下是由 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 (将#修改为@)