Dispatch::Semaphore Class

Watson1978 edited this page Jul 16, 2012 · 1 revision

Dispatch::Semaphore provides an efficient mechanism to synchronizes threads via a combination of waiting and signaling.

This is especially useful for controlling access to limited resources.

Methods in Dispatch::Semaphore class

Dispatch::Semaphore.new

Creates a new Dispatch::Semaphore object. This method is declared in GCD API as dispatch_semaphore_create.

  • new(count) -> Semaphore
    • [PARAM] count:
      • Specify the initial count value for semaphore.
    • [RETURN]
      • Returns a Dispatch::Semaphore instance.

Dispatch::Semaphore#wait

Waits (blocks the thread) Waits (blocks the thread) until the semaphore count value is increased greater than 0. When the semaphore count is equal to or greater than 1, cancels the wait status and the semaphore count is decreased. This method is declared in GCD API as dispatch_semaphore_wait.

  • wait(timeout = Dispatch::TIME_FOREVER) -> bool
    • [PARAM] timeout:
      • Specify a timeout. The default value is Dispatch::TIME_FOREVER.
    • [RETURN]
      • Returns a true if canceled waiting status, false if timed out.
gcdq = Dispatch::Queue.new('sample')
sema = Dispatch::Semaphore.new(0)
gcdq.async {
  sleep 1
  puts "Hello"
  sema.signal
}
sema.wait #=> true

Dispatch::Semaphore#signal

Increases the semaphore count. This method is declared in GCD API as dispatch_semaphore_signal.

  • signal -> bool
    • [RETURN]
      • Returns a true if no thread is waiting, otherwise false