gpt4 book ai didi

ios - 等待超时时发送信号量信号

转载 作者:搜寻专家 更新时间:2023-10-30 22:28:42 28 4
gpt4 key购买 nike

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.

关于ios - 等待超时时发送信号量信号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29361996/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com