Skip to content

Instantly share code, notes, and snippets.

@benoittgt
Created February 22, 2024 20:57
Show Gist options
  • Save benoittgt/c87bad638ae4a6a70706292a770983d5 to your computer and use it in GitHub Desktop.
Save benoittgt/c87bad638ae4a6a70706292a770983d5 to your computer and use it in GitHub Desktop.
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
def schedule(*args, &block)
@jobs << [block, args]
end
def run!
@size.times do
schedule { throw :exit }
end
@pool.map(&:join)
end
end
require 'net/http'
pool = ThreadPool.new(25)
200.times { |i| pool.schedule { p Net::HTTP.get(URI("https://api.github.com/users?since=#{i}")) } }
# congratulations you are ratelimited 😅
pool.run!
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment