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