Skip to content

Instantly share code, notes, and snippets.

@AaronM04
Created January 8, 2018 19:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save AaronM04/98676c7169d2b7e75cfea84248e740c2 to your computer and use it in GitHub Desktop.
Save AaronM04/98676c7169d2b7e75cfea84248e740c2 to your computer and use it in GitHub Desktop.
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