2015-05-16 63 views
0

如何用條件變量替換下面的忙等待?用條件變量替換忙等待

while (this_thread != pthread_self()){ 
     pthread_mutex_lock(&lock); 
     if(this_thread == -1) 
      this_thread = get_id(); 
     pthread_mutex_unlock(&lock); 
    } 

謝謝!

+0

如何設置由'get_id()'返回的值? – alk

回答

2

假設由get_id()返回的值是只能通過一個名爲set_id()功能集,請參閱本僞代碼:

全局

Mutex mutex 
Condition cond 
Id id 

代碼

set_id(id_in) 
{ 
    mutex_lock 
    id = id_in 
    cond_signal 
    mutex_unlock 
} 

test() 
{ 
    mutex_lock 
    while ((this_thread = get_id()) != pthread_self()) 
    cond_wait 
    mutex_unlock 
}