Last active
January 26, 2023 11:40
-
-
Save Galaxy83/f7d875cddad5c2999fe18748478a22c6 to your computer and use it in GitHub Desktop.
Ruby Each in Thread implementation - each_in_thread - Good for concurrent API calls.
This file contains hidden or 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
# frozen_string_literal: true | |
require 'thread/pool' | |
# Install Gem 'thread' or add it to your Gemfile. | |
# | |
# Example: | |
# | |
# ids = [1,2,3,4,5,6,7,8,9,10] | |
# ids.each_in_thread(concurrency: 20) do |id| | |
# Http.put("https://api.example.items/#{id}", {updated: true}) | |
# end | |
module Enumerable | |
def each_in_thread(concurrency: 10, count_each: 1) | |
pool = Thread.pool(concurrency) | |
done = 0 | |
self.each_with_index do |item, i| | |
pool.process do | |
yield item, i | |
print "completed #{done} / #{self.size}\r" if (done += 1) % count_each == 0 | |
end | |
end | |
pool.shutdown | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment