2015-03-31 100 views

回答

8

dispatch_semaphore_wait()遞減計數信號量並等待 如果結果值小於零。如果發生超時,這個遞減量會反轉,所以您不必手動調整計數。

從文檔中看不出(對我而言),但與 一致,負數表示線程正在等待 信號量。另見the source code此評論:

// If the internal value is negative, then the absolute of the value is 
// equal to the number of waiting threads. ... 

您也可以通過打印 信號的debugDescription驗證,輸出顯示當前值:

let sem = dispatch_semaphore_create(0) 

NSLog("%@", sem.debugDescription) 
// <OS_dispatch_semaphore: semaphore[0x100514a70] = { ..., value = 0, orig = 0 }> 
// --> Initial value is 0 

dispatch_after(dispatch_time(DISPATCH_TIME_NOW, Int64(NSEC_PER_SEC)), 
    dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)) { 
     NSLog("%@", sem.debugDescription) 
     // <OS_dispatch_semaphore: semaphore[0x100514a70] = { ..., value = -1, orig = 0 }> 
     // --> One thread is waiting, value is -1. 
} 

let ret = dispatch_semaphore_wait(sem, dispatch_time(DISPATCH_TIME_NOW, 2*Int64(NSEC_PER_SEC))) 
NSLog("%@", sem.debugDescription) 
// <OS_dispatch_semaphore: semaphore[0x100514a70] = { ..., value = 0, orig = 0 }> 
// --> Time out, value is 0 again.