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?, #pop, #signal, #size, #wait

Constructor Details

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

Create a new limited queue.



112
113
114
115
116
117
# File 'lib/async/queue.rb', line 112

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.



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

def limit
  @limit
end

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



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

attr :limit

Instance Method Details

#dequeueObject

Remove and return the next item from the queue.

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



163
164
165
166
167
168
169
# File 'lib/async/queue.rb', line 163

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.



145
146
147
148
149
150
151
152
153
154
155
156
# File 'lib/async/queue.rb', line 145

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)


123
124
125
# File 'lib/async/queue.rb', line 123

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

#push(item) ⇒ Object

Add an item to the queue.

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



132
133
134
135
136
137
138
# File 'lib/async/queue.rb', line 132

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