首页 > 解决方案 > 首次调用信号时如何使用 Dispatch_Sempahore

问题描述

在 DispatchSemaphore 函数中,可以先调用 Signal() 再调用 Wait() 吗?如果连续调用Signal() N,内部的值是不是变成了N,或者我想知道如果不调用Wait(),多次调用Signal()不会增加值。

let sempahore = DispatchSemaphore(value: 0)
semaphore.signal()
semaphore.signal()
semaphore.signal()
// in time, what is sempahore value? 1 or 3?

sempahore.wait()
// in time, what is semaphore value? 0 or 2?
// wait for more signal? or not?

标签: swiftdispatchsemaphore

解决方案


每一个.signal都是'+1',每一个.wait都是'-1'或block如记录的那样,演示的代码是

let semaphore = DispatchSemaphore(value: 0)
semaphore.signal() // = 1
semaphore.signal() // = 2
semaphore.signal() // = 3

semaphore.wait() // = 2  - pass
semaphore.wait() // = 1  - pass
semaphore.wait() // = 0  - pass
semaphore.wait() // = -1 - hang - waiting for new signal()

这是来自Apple 文档

您可以通过调用 signal() 方法来增加信号量计数,并通过调用 wait() 或其指定超时的变体之一来减少信号量计数。

@discardableResult func signal() -> Int
Discussion
Increment the counting semaphore. If the previous value was less than zero, 
  this function wakes a thread currently waiting

func wait()
Discussion
Decrement the counting semaphore. If the resulting value is less than zero, 
  this function waits for a signal to occur before returning.

推荐阅读