99
1010module Async
1111 # A queue which allows items to be processed in order.
12+ #
13+ # It has a compatible interface with {Notification} and {Condition}, except that it's multi-value.
14+ #
1215 # @public Since `stable-v1`.
13- class Queue < Notification
16+ class Queue
1417 # Create a new queue.
1518 #
1619 # @parameter parent [Interface(:async) | Nil] The parent task to use for async operations.
17- def initialize ( parent : nil )
18- super ( )
19-
20+ # @parameter available [Notification] The notification to use for signaling when items are available.
21+ def initialize ( parent : nil , available : Notification . new )
2022 @items = [ ]
2123 @parent = parent
24+ @available = available
2225 end
2326
2427 # @attribute [Array] The items in the queue.
@@ -38,20 +41,20 @@ def empty?
3841 def <<( item )
3942 @items << item
4043
41- self . signal unless self . empty?
44+ @available . signal unless self . empty?
4245 end
4346
4447 # Add multiple items to the queue.
4548 def enqueue ( *items )
4649 @items . concat ( items )
4750
48- self . signal unless self . empty?
51+ @available . signal unless self . empty?
4952 end
5053
5154 # Remove and return the next item from the queue.
5255 def dequeue
5356 while @items . empty?
54- self . wait
57+ @available . wait
5558 end
5659
5760 @items . shift
@@ -77,6 +80,16 @@ def each
7780 yield item
7881 end
7982 end
83+
84+ # Signal the queue with a value, the same as {#enqueue}.
85+ def signal ( value )
86+ self . enqueue ( value )
87+ end
88+
89+ # Wait for an item to be available, the same as {#dequeue}.
90+ def wait
91+ self . dequeue
92+ end
8093 end
8194
8295 # A queue which limits the number of items that can be enqueued.
@@ -85,12 +98,12 @@ class LimitedQueue < Queue
8598 # Create a new limited queue.
8699 #
87100 # @parameter limit [Integer] The maximum number of items that can be enqueued.
88- def initialize ( limit = 1 , **options )
101+ # @parameter full [Notification] The notification to use for signaling when the queue is full.
102+ def initialize ( limit = 1 , full : Notification . new , **options )
89103 super ( **options )
90104
91105 @limit = limit
92-
93- @full = Notification . new
106+ @full = full
94107 end
95108
96109 # @attribute [Integer] The maximum number of items that can be enqueued.
@@ -128,7 +141,7 @@ def enqueue(*items)
128141 available = @limit - @items . size
129142 @items . concat ( items . shift ( available ) )
130143
131- self . signal unless self . empty?
144+ @available . signal unless self . empty?
132145 end
133146 end
134147
0 commit comments