class SyncQueue

Attributes

queue[RW]

Public Class Methods

new(max_size=nil) click to toggle source
# File lib/devp2p/sync_queue.rb, line 8
def initialize(max_size=nil)
  @queue = []
  @num_waiting = 0

  @max_size = max_size

  @mutex = Mutex.new
  @cond_full = ConditionVariable.new
  @cond_empty = ConditionVariable.new
end

Public Instance Methods

<<(obj, non_block=false)
Alias for: enq
clear() click to toggle source
# File lib/devp2p/sync_queue.rb, line 102
def clear
  @queue.clear
end
deq(non_block=false) click to toggle source
# File lib/devp2p/sync_queue.rb, line 45
def deq(non_block=false)
  Thread.handle_interrupt(StandardError => :on_blocking) do
    loop do
      @mutex.synchronize do
        if empty?
          if non_block
            raise ThreadError, 'queue empty'
          else
            begin
              @num_waiting += 1
              @cond_empty.wait @mutex
            ensure
              @num_waiting -= 1
            end
          end
        else
          obj = @queue.shift
          @cond_full.signal
          return obj
        end
      end
    end
  end
end
empty?() click to toggle source
# File lib/devp2p/sync_queue.rb, line 98
def empty?
  @queue.empty?
end
enq(obj, non_block=false) click to toggle source
# File lib/devp2p/sync_queue.rb, line 19
def enq(obj, non_block=false)
  Thread.handle_interrupt(StandardError => :on_blocking) do
    loop do
      @mutex.synchronize do
        if full?
          if non_block
            raise ThreadError, 'queue full'
          else
            begin
              @num_waiting += 1
              @cond_full.wait @mutex
            ensure
              @num_waiting -= 1
            end
          end
        else
          @queue.push obj
          @cond_empty.signal
          return obj
        end
      end
    end
  end
end
Also aliased as: <<
full?() click to toggle source
# File lib/devp2p/sync_queue.rb, line 94
def full?
  @max_size && @queue.size >= @max_size
end
length() click to toggle source
# File lib/devp2p/sync_queue.rb, line 106
def length
  @queue.length
end
Also aliased as: size
num_waiting() click to toggle source

Returns the number of threads waiting on the queue.

# File lib/devp2p/sync_queue.rb, line 112
def num_waiting
  @num_waiting
end
peek(non_block=false) click to toggle source

Same as pop except it will not remove the element from queue, just peek.

# File lib/devp2p/sync_queue.rb, line 71
def peek(non_block=false)
  Thread.handle_interrupt(StandardError => :on_blocking) do
    loop do
      @mutex.synchronize do
        if empty?
          if non_block
            raise ThreadError, 'queue empty'
          else
            begin
              @num_waiting += 1
              @cond_empty.wait @mutex
            ensure
              @num_waiting -= 1
            end
          end
        else
          return @queue[0]
        end
      end
    end
  end
end
size()
Alias for: length