OSDN Git Service

Replaced mongrel with thin
[redminele/redminele.git] / ruby / lib / ruby / gems / 1.8 / gems / eventmachine-0.12.10-x86-mswin32-60 / lib / em / queue.rb
1 module EventMachine
2   # A cross thread, reactor scheduled, linear queue.
3   #
4   # This class provides a simple "Queue" like abstraction on top of the reactor
5   # scheduler. It services two primary purposes:
6   # * API sugar for stateful protocols
7   # * Pushing processing onto the same thread as the reactor
8   #
9   # See examples/ex_queue.rb for a detailed example.
10   #
11   #  q = EM::Queue.new
12   #  q.push('one', 'two', 'three')
13   #  3.times do
14   #    q.pop{ |msg| puts(msg) }
15   #  end
16   #
17   class Queue
18     # Create a new queue
19     def initialize
20       @items = []
21       @popq  = []
22     end
23
24     # Pop items off the queue, running the block on the reactor thread. The pop
25     # will not happen immediately, but at some point in the future, either in 
26     # the next tick, if the queue has data, or when the queue is populated.
27     def pop(*a, &b)
28       cb = EM::Callback(*a, &b)
29       EM.schedule do
30         if @items.empty?
31           @popq << cb
32         else
33           cb.call @items.shift
34         end
35       end
36       nil # Always returns nil
37     end
38
39     # Push items onto the queue in the reactor thread. The items will not appear
40     # in the queue immediately, but will be scheduled for addition during the 
41     # next reactor tick.
42     def push(*items)
43       EM.schedule do
44         @items.push(*items)
45         @popq.shift.call @items.shift until @items.empty? || @popq.empty?
46       end
47     end
48
49     # N.B. This is a peek, it's not thread safe, and may only tend toward 
50     # accuracy.
51     def empty?
52       @items.empty?
53     end
54
55     # N.B. This is a peek, it's not thread safe, and may only tend toward 
56     # accuracy.
57     def size
58       @items.size
59     end
60   end
61 end