Sha256: 1cb69d87c5fe403250d5f841d300669ecd46346743821254a06be2c06569c271

Contents?: true

Size: 1.01 KB

Versions: 16

Compression:

Stored size: 1.01 KB

Contents

description 'Semaphore class'

# Semaphore implementation based on {Mutex} and {ConditionVariable}.
# A mutex allows a number of threads to enter a synchronized section in parallel.
class Semaphore
  # @param [Integer] counter Number of threads which can enter the section in parallel
  def initialize(counter = 1)
    @mutex = Mutex.new
    @cond = ConditionVariable.new
    @counter = counter
  end

  # Enter synchronized section
  #
  # Decrements the semaphore counter
  #
  # @api public
  # @return [void]
  def enter
    @mutex.synchronize do
      @cond.wait(@mutex) if (@counter -= 1) < 0
    end
  end

  # Leave synchronized section
  #
  # Increments the semaphore counter
  #
  # @api public
  # @return [void]
  def leave
    @mutex.synchronize do
      @cond.signal if (@counter += 1) <= 0
    end
  end

  # Synchronize block with this semaphore
  #
  # @api public
  # @yield Block to synchronize
  # @return [void]
  def synchronize
    enter
    yield
  ensure
    leave
  end
end

Olelo::Semaphore = Semaphore

Version data entries

16 entries across 16 versions & 1 rubygems

Version Path
olelo-0.9.15 plugins/utils/semaphore.rb
olelo-0.9.14 plugins/utils/semaphore.rb
olelo-0.9.13 plugins/utils/semaphore.rb
olelo-0.9.12 plugins/utils/semaphore.rb
olelo-0.9.11 plugins/utils/semaphore.rb
olelo-0.9.10 plugins/utils/semaphore.rb
olelo-0.9.9 plugins/utils/semaphore.rb
olelo-0.9.8 plugins/utils/semaphore.rb
olelo-0.9.7 plugins/utils/semaphore.rb
olelo-0.9.6 plugins/utils/semaphore.rb
olelo-0.9.5 plugins/utils/semaphore.rb
olelo-0.9.4 plugins/utils/semaphore.rb
olelo-0.9.3 plugins/utils/semaphore.rb
olelo-0.9.2 plugins/utils/semaphore.rb
olelo-0.9.1 plugins/utils/semaphore.rb
olelo-0.9.0 plugins/utils/semaphore.rb