gpt4 book ai didi

填充所有缓冲区的算法生产者-消费者

转载 作者:塔克拉玛干 更新时间:2023-11-03 05:23:32 32 4
gpt4 key购买 nike

我正在阅读著名的操作系统概念书(Avi Silberschatz、Peter Baer Galvin、Greg Gagne)第 9 版:http://codex.cs.yale.edu/avi/os-book/OS9/

书中第5节“进程同步”中,有如下例子:

Suppose that we wanted to provide a solution to the consumer-producer problem that fills all the buffers. We can do so by having an integer counter that keeps track of the number of full buffers. Initially, counter is set to 0. It is incremented by the producer after it produces a new buffer and is decremented by the consumer after it consumes a buffer.

这个问题的算法如下:

生产者算法:

while (true)
{
/* produce an item in nextproduced */

while (counter == BUFFER_SIZE) ;
/* do nothing */

buffer[in] = next_produced;
in = (in + 1) % BUFFER_SIZE;
counter++;
}

消费者算法:

while (true)
{
while (counter == 0) ; /* do nothing */

next_consumed = buffer[out];

out = (out + 1) % BUFFER_SIZE;
counter--;
/* consume the item in next consumed */
}

您可以在进程同步章节的幻灯片中找到这些算法:http://codex.cs.yale.edu/avi/os-book/OS9/slide-dir/PPT-dir/ch5.ppt

我不明白这些算法应该如何填充所有缓冲区。据我所知,它们只填充一个缓冲区。我是对的还是我错过了什么?这些算法至少从2007年开始就在书中提到了,所以我想应该没有错误,但我误解了它们?

欢迎任何解释。

最佳答案

好的,我明白了,问题出在变量的语义上。next_produced 变量将直接填充一个完整的缓冲区,因此 buffer[] 是一个“BUFFER_SIZE”缓冲区数组,生产者中的每个循环都会产生一个 next_produced 项,它将直接填充整个缓冲区(元素)int缓冲区 [] 数组。

关于填充所有缓冲区的算法生产者-消费者,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23582809/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com