4
當dispatch_semaphore_wait
發生超時時,它會自動發出信號(增加計數)還是手動完成此操作?在等待超時時發送信號燈信號
當dispatch_semaphore_wait
發生超時時,它會自動發出信號(增加計數)還是手動完成此操作?在等待超時時發送信號燈信號
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.