如何工作 Dispatch_Sempahore 当第一次呼叫信号和

How to work Dispatch_Sempahore when first call signal and

在 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?

每个 .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 Documentation

You increment a semaphore count by calling the signal() method, and decrement a semaphore count by calling wait() or one of its variants that specifies a timeout.

@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.