Class: Async::LimitedQueue

Inherits:
Queue
  • Object
show all
Defined in:
lib/async/queue.rb

Overview

A queue which limits the number of items that can be enqueued.

Instance Attribute Summary collapse

Attributes inherited from Queue

#The items in the queue., #items

Instance Method Summary collapse

Methods inherited from Queue

#async, #each, #empty?, #push, #signal, #size, #wait

Constructor Details

#initialize(limit = 1, full: Notification.new, **options) ⇒ LimitedQueue

Create a new limited queue.



108
109
110
111
112
113
# File 'lib/async/queue.rb', line 108

def initialize(limit = 1, full: Notification.new, **options)
	super(**options)
	
	@limit = limit
	@full = full
end

Instance Attribute Details

#limitObject (readonly)

Returns the value of attribute limit.



116
117
118
# File 'lib/async/queue.rb', line 116

def limit
  @limit
end

#The maximum number of items that can be enqueued.(maximumnumberofitemsthatcanbeenqueued.) ⇒ Object (readonly)



116
# File 'lib/async/queue.rb', line 116

attr :limit

Instance Method Details

#<<(item) ⇒ Object

Add an item to the queue.

If the queue is full, this method will block until there is space available.



128
129
130
131
132
133
134
# File 'lib/async/queue.rb', line 128

def <<(item)
	while limited?
		@full.wait
	end
	
	super
end

#dequeueObject

Remove and return the next item from the queue.

If the queue is empty, this method will block until an item is available.



159
160
161
162
163
164
165
# File 'lib/async/queue.rb', line 159

def dequeue
	item = super
	
	@full.signal
	
	return item
end

#enqueue(*items) ⇒ Object

Add multiple items to the queue.

If the queue is full, this method will block until there is space available.



141
142
143
144
145
146
147
148
149
150
151
152
# File 'lib/async/queue.rb', line 141

def enqueue(*items)
	while !items.empty?
		while limited?
			@full.wait
		end
		
		available = @limit - @items.size
		@items.concat(items.shift(available))
		
		@available.signal unless self.empty?
	end
end

#limited?Boolean

Returns:

  • (Boolean)


119
120
121
# File 'lib/async/queue.rb', line 119

def limited?
	@items.size >= @limit
end