【发布时间】:2016-01-15 06:11:59
【问题描述】:
在操作系统概念(Silberschatz,第 9 版)的第 3.4.1 节中,作者提出了生产者-消费者问题并给出了以下使用循环缓冲区的实现(第 125、126 页)。
//Shared variables
#define BUFFER SIZE 10
struct Item;
Item buffer[BUFFER SIZE];
int in = 0, out = 0;
//buffer is empty when in == out
//buffer is full when (in + 1) % BUFFER SIZE == out
//Producer
while (true)
{
Item next_produced = /*produce item here*/;
while (((in + 1) % BUFFER SIZE) == out) ; //do nothing
buffer[in] = next_produced;
in = (in + 1) % BUFFER SIZE;
}
//Consumer
while (true)
{
while (in == out) ; //do nothing
Item next_consumed = buffer[out];
out = (out + 1) % BUFFER SIZE;
//consume the item in next_consumed here
}
书上说:
此插图未解决的一个问题涉及 生产者进程和消费者进程都试图 同时访问共享缓冲区。
我看不到生产者和消费者会同时访问相同缓冲区元素的情况。
我的问题是:如果生产者和消费者在两个线程中运行,那么这个实现中是否存在竞争条件或其他同步问题?
【问题讨论】:
标签: c multithreading producer-consumer