smallest thread pool in ruby


class ThreadPool
attr_accessor :threads, :max_size
def initialize max_size=4
@max_size = max_size
@threads = []
end
def start *args, &block
while(threads.count>=max_size) do
threads.select!{ |thr| !thr.stop? }
sleep(0.1)
end
threads << Thread.new(args) do |args|
begin
args = args[0] if args.length==1
yield args
rescue Exception => e
puts e.message
puts e.backtrace
end
end
end
def join
threads.map(&:join)
end
end
# p = ThreadPool.new
# 1.upto(10) do |i|
# p.start(i) do |a|
# $stdout.flush
# puts "p #{a}"
# end
# end
# p.join

view raw

thread_pool.rb

hosted with ❤ by GitHub