Skip to content

Instantly share code, notes, and snippets.

@dux
Last active November 10, 2017 11:00
Show Gist options
  • Save dux/2e6aacd107d0a9812ecd5dd5865e36be to your computer and use it in GitHub Desktop.
Save dux/2e6aacd107d0a9812ecd5dd5865e36be to your computer and use it in GitHub Desktop.
Simple thread poll
require 'colorize'
# require 'thread/pool'
# pool = Thread.pool(3)
pool = ThreadPool.new 3
1.upto(10).to_a.each { |num|
pool.process do
sleep_for = (rand()*10).to_i
text = "#{num} sleep #{sleep_for}"
puts "START #{text}".red
sleep sleep_for
puts "END #{text}".green
end
}
pool.shutdown
require 'thread'
class ThreadPool
def initialize max_threads = 5
@pool = SizedQueue.new max_threads
max_threads.times{ @pool << 1 }
@mutex = Mutex.new
@running_threads = []
end
def process &block
@pool.pop
@mutex.synchronize do
@running_threads << Thread.start do
begin
block.call
rescue Exception => e
puts "Exception: #{e.message}\n#{e.backtrace}"
ensure
@pool << 1
end
end
end
end
def shutdown
@running_threads.each &:join
end
end
class ThreadPool
def initialize parallel
@parallel = parallel
@running = 0
@pool = []
@threads = []
@mutex = Mutex.new # synchronize
end
def process func=nil, &block
@pool.push func || block
end
def run!
return shutdown unless @pool[0]
if @running < @parallel
@mutex.synchronize { @running += 1 }
@threads << Thread.new {
@pool.shift.call
@mutex.synchronize { @running -= 1 }
}
else
sleep 1.0/100
end
run!
end
def shutdown
return run! if @pool[0]
@threads.each(&:join)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment