您可以打印
semaphore.debugDescription
或使用
debugPrint
:
let semaphore = DispatchSemaphore(value: 3)
debugPrint(semaphore) // <OS_dispatch_semaphore: semaphore[0x6000024dd590] = { xref = 2, ref = 1, port = 0x0, value = 3, orig = 3 }>
semaphore.wait()
debugPrint(semaphore) // <OS_dispatch_semaphore: semaphore[0x6000024dd590] = { xref = 2, ref = 1, port = 0x0, value = 2, orig = 3 }>
semaphore.wait()
debugPrint(semaphore) // <OS_dispatch_semaphore: semaphore[0x6000024dd590] = { xref = 2, ref = 1, port = 0x0, value = 1, orig = 3 }>
semaphore.signal()
debugPrint(semaphore) // <OS_dispatch_semaphore: semaphore[0x6000024dd590] = { xref = 2, ref = 1, port = 0x0, value = 2, orig = 3 }>
semaphore.signal()
debugPrint(semaphore) // <OS_dispatch_semaphore: semaphore[0x6000024dd590] = { xref = 2, ref = 1, port = 0x0, value = 3, orig = 3 }>
不过,仅用于诊断目的。他们故意不将此计数器值作为财产公开。
值得一提的是,我可能建议不要使用信号量来限制对共享资源的并发访问。通常,我们更喜欢其他模式,如actor、锁、串行GCD队列或读写器模式。
我也可能建议不要使用信号量,以避免线程爆炸。同样,还有更好、更现代的模式,从GCD
concurrentPerform
,
OperationQueue
及其
maxConcurrentOperationCount
,Swift并发的协作线程池,Combines max publishers模式等(FWIW,这些模式中的大多数也不公开当前计数。)
简言之,如今许多人认为信号量有点反模式。但如果你想看看计数,
debugPrint
(或明确访问
debugDescription
)会告诉你发生了什么。