2016-12-07 1 views
0

cond 변수와 세마포어를 사용하여 생산자 소비자 문제 구현을 비교하려고합니다.sem_wait에서 while 루프가 필요하지 않은 이유는 무엇입니까?

구현하여 COND 변수 :

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 버전처럼 내부적으로 꽉 루프를 사용하지,하지만 것 바쁜 루프와 같은 자원을 낭비하지에이 각 반복에 다시 스케줄러로 실행을 얻을 수 있습니다.

스케줄러가 잠시 다른 프로세스를 실행하면 스레드로 다시 실행됩니다. 세마포어를 지금 사용할 수 있으면 가져옵니다. 그렇지 않으면 다른 프로세스가 다시 시도하기 전에 더 많은 프로세스를 실행할 수 있도록 스케줄러로 되돌아갑니다.

관련 문제