Skip to content

Instantly share code, notes, and snippets.

@Galaxy83
Last active January 26, 2023 11:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Galaxy83/f7d875cddad5c2999fe18748478a22c6 to your computer and use it in GitHub Desktop.
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.
# 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