Class: PriorityQueue

Inherits:
Object show all
Defined in:
lib/carat-dev/priority-queue/priorityqueue.rb

Instance Method Summary collapse

Constructor Details

#initialize(*classes) ⇒ PriorityQueue

Returns a new instance of PriorityQueue.



5
6
7
8
9
10
11
# File 'lib/carat-dev/priority-queue/priorityqueue.rb', line 5

def initialize (*classes)
  @order = classes
  @queues = Hash::new
  classes.each { |c| @queues[c] = Queue::new }
  @ilimit = @order.size
  @waiting = []
end

Instance Method Details

#clearObject



65
66
67
# File 'lib/carat-dev/priority-queue/priorityqueue.rb', line 65

def clear
  @queues.each_value { |q| q.clear }
end

#empty?Boolean

Returns:

  • (Boolean)


59
60
61
62
63
# File 'lib/carat-dev/priority-queue/priorityqueue.rb', line 59

def empty?
  epty = true
  @queues.each_value { |q| epty = epty and q.empty? }
  return epty
end

#lengthObject



69
70
71
72
73
# File 'lib/carat-dev/priority-queue/priorityqueue.rb', line 69

def length
  l = 0
  @queues.each_value { |q| l += q.length }
  return l
end

#num_waitingObject



79
80
81
# File 'lib/carat-dev/priority-queue/priorityqueue.rb', line 79

def num_waiting
  @waiting.size
end

#pop(non_block = false) ⇒ Object Also known as: shift, deq



34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
# File 'lib/carat-dev/priority-queue/priorityqueue.rb', line 34

def pop(non_block=false)
  Thread.critical = true
  begin
    loop do
	i = 0
	while (i < @ilimit) and (@queues[@order[i]].empty?)
 i = i + 1
	end
	if i == @ilimit
 if non_block
   raise ThreadError, "queue empty"
 end
 @waiting.push Thread.current
 Thread.stop
	else
 return @queues[@order[i]].shift
	end
    end
  ensure
    Thread.critical = false
  end
end

#push(obj) ⇒ Object Also known as: <<, enq



13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
# File 'lib/carat-dev/priority-queue/priorityqueue.rb', line 13

def push (obj)
  Thread.critical = true
  begin
    @queues[obj.class.to_s].push obj
    t = @waiting.shift
    t.wakeup if t
  rescue ThreadError
    retry
  rescue NameError
    raise NameError, "unknown class queue"
  ensure
    Thread.critical = false
  end
  begin
    t.run if t
  rescue ThreadError
  end
end

#sizeObject



75
76
77
# File 'lib/carat-dev/priority-queue/priorityqueue.rb', line 75

def size
  length
end