Skip to content

Instantly share code, notes, and snippets.

@amolpujari
Last active August 7, 2020 06:38
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save amolpujari/7369418 to your computer and use it in GitHub Desktop.
Save amolpujari/7369418 to your computer and use it in GitHub Desktop.
smallest thread pool in ruby
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