Last active
August 7, 2020 06:38
-
-
Save amolpujari/7369418 to your computer and use it in GitHub Desktop.
smallest thread pool in ruby
This file contains hidden or 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
class ThreadPool | |
attr_accessor :threads, :max_size, :wait_time_to_free, :name | |
def initialize max_size=4 | |
@max_size = max_size | |
@threads = [] | |
@wait_time_to_free = 0.1 | |
end | |
def start *args, &block | |
while(threads.length>=max_size) do | |
threads.select!{ |thr| !thr.stop? } | |
sleep(wait_time_to_free) | |
end | |
threads << Thread.new(args) do |args| | |
begin | |
yield *args | |
rescue Exception => e | |
puts e.message | |
puts e.backtrace | |
end | |
ActiveRecord::Base.connection.close if defined? ActiveRecord | |
end | |
end | |
def join | |
threads.map(&:join) | |
end | |
end | |
# p = ThreadPool.new | |
# 1.upto(10) do |i| | |
# p.start(i, 1) do |a, b| | |
# puts | |
# $stdout.flush | |
# puts "p #{a} #{b}" | |
# end | |
# end | |
# p.join | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment