[英]Dispatch semaphore signal on wait timeout
当dispatch_semaphore_wait
运行到超时时,它会自动发出信号(增加计数),还是手动完成?
dispatch_semaphore_wait()
递减计数信号量,并等待结果值小于零。 如果发生超时,则此减量会反转,因此您无需手动调整计数。
对于我来说,这对文档来说并不明显,但与负数一致表明线程正在等待信号量的事实一致。 另请参阅源代码中的此注释:
// 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.
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.