Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Simple Ruby thread pool
class ThreadPool
def initialize(num_threads)
@tasks = Queue.new # contains either blocks to run, or :terminate
@threads = []
@terminated = false # only used to stop new work from being enqueued
num_threads.times do
@threads << Thread.new{ process }.run
end
end
def run(&block)
raise "cannot add new work while awaiting completion" if @terminated
@tasks << block
end
def await_completion
@terminated = true
@threads.count.times do
@tasks << :terminate
end
@threads.each do |thread|
thread.join
end
end
private
def process
# worker thread run loop
while true
item = @tasks.pop # will block if nothing in task queue
break if item == :terminate
item[]
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.