wikipedia中提及的生产者消费者问题的“执行不力”的伪代码如下。据说这种解决方案具有可能导致死锁的竞态条件。多线程编程 - 生产者消费者
我的问题是:不只是修改唤醒其他线程的条件如下解决了可能的死锁问题。这样就不会有一个可能会丢失的唤醒,但随后会有多个唤醒,或者我错过了一些东西。尝试在这里了解。
int itemCount = 0;
procedure producer() {
while (true) {
item = produceItem();
if (itemCount == BUFFER_SIZE) {
sleep();
}
putItemIntoBuffer(item);
itemCount = itemCount + 1;
//if (itemCount == 1) <<<<<<<< change this to below condition
if(itemCount > 0)
{
wakeup(consumer);
}
}
}
procedure consumer() {
while (true) {
if (itemCount == 0) {
sleep();
}
item = removeItemFromBuffer();
itemCount = itemCount - 1;
//if (itemCount == BUFFER_SIZE - 1) <<<<<<< Change this to below
if(itermCount < BUFFER_SIZE)
{
wakeup(producer);
}
consumeItem(item);
}
}
也修改'itemCount'的所有行都需要是原子的或锁定的。 – Adam
刚修复@Adam。谢谢。 – Gray
在多个消费者生产者的情况下不应该将唤醒发送到所有线程?那样可以避免比赛? – goldenmean