Class: EventMachine::PriorityQueue

Inherits:
Object
  • Object
show all
Includes:
Enumerable
Defined in:
lib/em-priority-queue/version.rb,
lib/em-priority-queue/priority_queue.rb

Constant Summary collapse

VERSION =
"1.1.2"

Instance Method Summary collapse

Constructor Details

#initialize(opts = {}, &blk) ⇒ PriorityQueue

Returns a new instance of PriorityQueue.



5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
# File 'lib/em-priority-queue/priority_queue.rb', line 5

def initialize(opts={}, &blk)
  blk ||= lambda { |x, y| (x <=> y) == 1 }
  fifo_blk = nil
  @fifo = !!opts[:fifo]
  if @fifo
    fifo_blk = lambda do |x,y|
      if x[0] == y[0]
        x[1] < y[1]
      else
        blk.call(x[0], y[0])
      end
    end
  end
  @heap = Algorithms::Containers::Heap.new(&(fifo_blk || blk))
  @callbacks = []
end

Instance Method Details

#clearObject



34
35
36
# File 'lib/em-priority-queue/priority_queue.rb', line 34

def clear
  @heap.clear
end

#delete(pri) ⇒ Object



62
63
64
# File 'lib/em-priority-queue/priority_queue.rb', line 62

def delete(pri)
  @heap.delete(pri)
end

#empty?Boolean

Returns:

  • (Boolean)


38
39
40
# File 'lib/em-priority-queue/priority_queue.rb', line 38

def empty?
  @heap.empty?
end

#has_priority?(priority) ⇒ Boolean

Returns:

  • (Boolean)


42
43
44
# File 'lib/em-priority-queue/priority_queue.rb', line 42

def has_priority?(priority)
  @heap.has_key?(priority)
end

#nextObject



46
47
48
# File 'lib/em-priority-queue/priority_queue.rb', line 46

def next
  @heap.next
end

#pop(*a, &c) ⇒ Object



50
51
52
53
54
55
56
57
58
59
60
# File 'lib/em-priority-queue/priority_queue.rb', line 50

def pop(*a, &c)
  cb = EM::Callback(*a, &c)
  EM.schedule do
    if @heap.empty?
      @callbacks << cb
    else
      cb.call @heap.pop
    end
  end
  nil
end

#push(obj, pri) ⇒ Object



26
27
28
29
30
31
32
# File 'lib/em-priority-queue/priority_queue.rb', line 26

def push(obj, pri)
  pri = [pri, Time.now.to_i] if @fifo
  EM.schedule do
    @heap.push(pri, obj)
    @callbacks.shift.call(@heap.pop) until @heap.empty? || @callbacks.empty?
  end
end

#sizeObject



22
23
24
# File 'lib/em-priority-queue/priority_queue.rb', line 22

def size
  @heap.size
end