swiftdispatchsemaphore

How to work Dispatch_Sempahore when first call signal and


During the DispatchSemaphore function, Is it OK to call Signal() first and Wait() later? If call Signal() N continuously, does the value internally become N, Or I wonder if invoking Signal() several times does not increase the value when Wait() is not called.

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?

Solution

  • Every .signal is '+1', and every .wait is '-1' or block as documented, and code that demo is

    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()
    

    Here is from 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.