AsyncSourceAsyncWorkerPool

class WorkerPool

A simple work pool that offloads work to a background thread.

Signature

private

Nested

Definitions

def initialize(size: Etc.nprocessors)

Create a new work pool.

Signature

parameter size Integer

The number of threads to use.

Implementation

def initialize(size: Etc.nprocessors)
	@ready = ::Thread::Queue.new
	
	size.times do
		@ready.push(Worker.new)
	end
end

def close

Close the work pool. Kills all outstanding work.

Implementation

def close
	if ready = @ready
		@ready = nil
		ready.close
		
		while worker = ready.pop
			worker.close
		end
	end
end

def call(work)

Offload work to a thread.

Signature

parameter work Proc

The work to be done.

Implementation

def call(work)
	if ready = @ready
		worker = ready.pop
		
		begin
			worker.call(work)
		ensure
			ready.push(worker)
		end
	else
		raise RuntimeError, "No worker available!"
	end
end

Discussion