Skip to content

Instantly share code, notes, and snippets.

@kopylovvlad
Created October 12, 2018 18:55
Show Gist options
  • Save kopylovvlad/dcf72c4c7f2f2879dac929d824b77d55 to your computer and use it in GitHub Desktop.
Save kopylovvlad/dcf72c4c7f2f2879dac929d824b77d55 to your computer and use it in GitHub Desktop.
# thread pool class
class ThreadPool
def initialize(size)
@size = size
@jobs = Queue.new
@pool = Array.new(@size) do |i|
Thread.new do
Thread.current[:id] = i
catch(:exit) do
loop do
job, args = @jobs.pop
job.call(*args)
end
end
end
end
end
# add a job to queue
def schedule(*args, &block)
@jobs << [block, args]
end
# run threads and perform jobs from queue
def run!
@size.times do
schedule { throw :exit }
end
@pool.map(&:join)
end
end
# an instance of ThreadPool with 5 threads
pool = ThreadPool.new(5)
# add 20 tasks to query
20.times do |i|
pool.schedule do
sleep_time = rand(4) + 2
sleep(sleep_time)
puts "Job #{i} with sleep time #{sleep_time}, finished by thread #{Thread.current[:id]}"
end
end
# run all threads
pool.run!
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment