Sha256: a353d8557e8bb04912a45c7f1b6789651497f31d5fcff9b412cbbb57c93db5e3

Contents?: true

Size: 1.26 KB

Versions: 39

Compression:

Stored size: 1.26 KB

Contents

module CopyTunerClient
  # https://spin.atomicobject.com/2014/07/07/ruby-queue-pop-timeout/
  class QueueWithTimeout
    def initialize
      @mutex = Mutex.new
      @queue = []
      @received = ConditionVariable.new
    end

    def <<(x)
      @mutex.synchronize do
        @queue << x
        @received.signal
      end
    end

    def uniq_push(x)
      @mutex.synchronize do
        unless @queue.member?(x)
          @queue << x
          @received.signal
        end
      end
    end

    def pop(non_block = false)
      pop_with_timeout(non_block ? 0 : nil)
    end

    def pop_with_timeout(timeout = nil)
      @mutex.synchronize do
        if timeout.nil?
          # wait indefinitely until there is an element in the queue
          while @queue.empty?
            @received.wait(@mutex)
          end
        elsif @queue.empty? && timeout != 0
          # wait for element or timeout
          timeout_time = timeout + Time.now.to_f
          while @queue.empty? && (remaining_time = timeout_time - Time.now.to_f) > 0
            @received.wait(@mutex, remaining_time)
          end
        end
        #if we're still empty after the timeout, raise exception
        raise ThreadError, "queue empty" if @queue.empty?
        @queue.shift
      end
    end
  end
end

Version data entries

39 entries across 39 versions & 1 rubygems

Version Path
copy_tuner_client-0.19.0 lib/copy_tuner_client/queue_with_timeout.rb
copy_tuner_client-0.18.0 lib/copy_tuner_client/queue_with_timeout.rb
copy_tuner_client-0.17.1 lib/copy_tuner_client/queue_with_timeout.rb
copy_tuner_client-0.16.3 lib/copy_tuner_client/queue_with_timeout.rb
copy_tuner_client-0.16.2 lib/copy_tuner_client/queue_with_timeout.rb
copy_tuner_client-0.16.1 lib/copy_tuner_client/queue_with_timeout.rb
copy_tuner_client-0.16.0 lib/copy_tuner_client/queue_with_timeout.rb
copy_tuner_client-0.15.1 lib/copy_tuner_client/queue_with_timeout.rb
copy_tuner_client-0.15.0 lib/copy_tuner_client/queue_with_timeout.rb
copy_tuner_client-0.14.2 lib/copy_tuner_client/queue_with_timeout.rb
copy_tuner_client-0.14.1 lib/copy_tuner_client/queue_with_timeout.rb
copy_tuner_client-0.14.0 lib/copy_tuner_client/queue_with_timeout.rb
copy_tuner_client-0.13.6 lib/copy_tuner_client/queue_with_timeout.rb
copy_tuner_client-0.13.5 lib/copy_tuner_client/queue_with_timeout.rb
copy_tuner_client-0.13.3 lib/copy_tuner_client/queue_with_timeout.rb
copy_tuner_client-0.13.2 lib/copy_tuner_client/queue_with_timeout.rb
copy_tuner_client-0.13.1 lib/copy_tuner_client/queue_with_timeout.rb
copy_tuner_client-0.13.0 lib/copy_tuner_client/queue_with_timeout.rb
copy_tuner_client-0.12.0 lib/copy_tuner_client/queue_with_timeout.rb
copy_tuner_client-0.11.0 lib/copy_tuner_client/queue_with_timeout.rb