Created
October 12, 2018 18:55
-
-
Save kopylovvlad/dcf72c4c7f2f2879dac929d824b77d55 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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