【发布时间】:2014-11-04 01:08:33
【问题描述】:
使用此信号量算法解决生产者-消费者问题,其中信号量按缓冲区大小递减,然后信号量减 1,表示临界区。
如果这些操作是背靠背连续发生的,为什么减 1(互斥体)然后减小缓冲区大小是不正确的?
我知道生产者和消费者会同时进入休眠状态,造成死锁,但为什么这个小开关会导致整个算法失败?
BufferSize = 3;
semaphore mutex = 1; // Controls access to critical section
semaphore empty = BufferSize; // counts number of empty buffer slots
semaphore full = 0; // counts number of full buffer slots
Producer()
{
int widget;
while (TRUE) { // loop forever
make_new(widget); // create a new widget to put in the buffer
down(&empty); // decrement the empty semaphore
down(&mutex); // enter critical section
put_item(widget); // put widget in buffer
up(&mutex); // leave critical section
up(&full); // increment the full semaphore
}
}
Consumer()
{
int widget;
while (TRUE) { // loop forever
down(&full); // decrement the full semaphore
down(&mutex); // enter critical section
remove_item(widget); // take a widget from the buffer
up(&mutex); // leave critical section
up(&empty); // increment the empty semaphore
consume_item(widget); // consume the item
}
}
代码来源:Resource
【问题讨论】: