Created
February 22, 2024 20:57
-
-
Save benoittgt/c87bad638ae4a6a70706292a770983d5 to your computer and use it in GitHub Desktop.
This file contains 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 | |
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