2016-12-07 4 views
0

cond変数とセマフォを使用して、プロデューサのコンシューマ問題の実装を比較しようとしています。 condの変数を使用してなぜsem_waitにwhileループが必要ないのですか?

実装:セマフォを使用して

acquire(m); // Acquire this monitor's lock. 
while (!p) { // While the condition/predicate/assertion that we are waiting for is not true... 
    wait(m, cv); // Wait on this monitor's lock and condition variable. 
} 
// ... Critical section of code goes here ... 
signal(cv2); -- OR -- notifyAll(cv2); // cv2 might be the same as cv or different. 
release(m); 

実装:

produce: 
    P(emptyCount) 
    P(useQueue) 
    putItemIntoQueue(item) 
    V(useQueue) 
    V(fullCount) 

なぜセマフォの実装はcondの変数の実装のように状態を確認するためにループしながら、使用されていませんか。?

while (!p) { // While the condition/predicate/assertion that we are waiting for is not true... 
     wait(m, cv); // Wait on this monitor's lock and condition variable. 
    } 

Why do you need a while loop while waiting for a condition variable

答えて

0

セマフォをつかむだけcondバージョンと同じように、内部的にタイトなループを使用していますが、それはビジーループのような資源を無駄にしないだろうし、各反復に戻っスケジューラに実行を与えます。

スケジューラがしばらくの間他のプロセスを実行すると、スレッドに実行が戻されます。セマフォが現在利用可能な場合は、セマフォを取得します。それ以外の場合は、スケジューラに戻り、他のプロセスをもう一度実行してから再試行します。

関連する問題