AsyncSourceAsyncLimitedQueue

class LimitedQueue

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

Signature

public

Since Async v1.

Definitions

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

Create a new limited queue.

Signature

parameter limit Integer

The maximum number of items that can be enqueued.

parameter full Notification

The notification to use for signaling when the queue is full.

Implementation

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

attr :limit

Signature

attribute Integer

The maximum number of items that can be enqueued.

def limited?

Signature

returns Boolean

Whether trying to enqueue an item would block.

Implementation

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

def <<(item)

Add an item to the queue.

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

Signature

parameter item Object

The item to add to the queue.

Implementation

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

def enqueue(*items)

Add multiple items to the queue.

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

Signature

parameter items Array

The items to add to the queue.

Implementation

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

def dequeue

Remove and return the next item from the queue.

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

Signature

returns Object

The next item in the queue.

Implementation

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

Discussion