Class: Async::WorkerPool

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

Overview

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

Defined Under Namespace

Modules: BlockingOperationWait Classes: Promise, Worker

Instance Method Summary collapse

Constructor Details

#initialize(size: Etc.nprocessors) ⇒ WorkerPool

Create a new work pool.



145
146
147
148
149
150
151
# File 'lib/async/worker_pool.rb', line 145

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

Instance Method Details

#call(work) ⇒ Object

Offload work to a thread.



168
169
170
171
172
173
174
175
176
177
178
179
180
# File 'lib/async/worker_pool.rb', line 168

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

#closeObject

Close the work pool. Kills all outstanding work.



154
155
156
157
158
159
160
161
162
163
# File 'lib/async/worker_pool.rb', line 154

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