Sha256: 5eda038ff10ddf556fc7865c869bff62a8565d803bc807da52945b7def33eaf4

Contents?: true

Size: 633 Bytes

Versions: 15

Compression:

Stored size: 633 Bytes

Contents

# frozen_string_literal: true

# A latch that allows you to wait for a maximum number of seconds.
class CountDownLatch
  def initialize(count)
    @count = count
    @mutex = Mutex.new
    @resource = ConditionVariable.new
  end

  def count_down
    @mutex.synchronize do
      if @count.positive?
        @count -= 1
        @resource.signal if @count.zero?
      end
      @count
    end
  end

  def count
    @mutex.synchronize { @count }
  end

  def await(timeout:)
    @mutex.synchronize do
      @resource.wait(@mutex, timeout) if @count.positive?
      raise 'timed out while waiting' unless @count.zero?
    end
  end
end

Version data entries

15 entries across 15 versions & 1 rubygems

Version Path
sqlui-0.1.84 app/count_down_latch.rb
sqlui-0.1.83 app/count_down_latch.rb
sqlui-0.1.82 app/count_down_latch.rb
sqlui-0.1.81 app/count_down_latch.rb
sqlui-0.1.80 app/count_down_latch.rb
sqlui-0.1.79 app/count_down_latch.rb
sqlui-0.1.78 app/count_down_latch.rb
sqlui-0.1.77 app/count_down_latch.rb
sqlui-0.1.76 app/count_down_latch.rb
sqlui-0.1.75 app/count_down_latch.rb
sqlui-0.1.74 app/count_down_latch.rb
sqlui-0.1.73 app/count_down_latch.rb
sqlui-0.1.72 app/count_down_latch.rb
sqlui-0.1.71 app/count_down_latch.rb
sqlui-0.1.70 app/count_down_latch.rb