Created
August 12, 2019 13:45
-
-
Save emad-elsaid/e08685e125b543bc38cf484b1e51265f 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 self.execute(objects:, method:, pool: 5) | |
new(objects: objects, method: method, pool: pool).execute | |
end | |
def initialize(objects:, method:, pool:) | |
@objects = objects | |
@method = method | |
@pool = pool | |
@queue = queue | |
end | |
def execute | |
(0...pool).map { thread }.map(&:join) | |
end | |
private | |
attr_reader :objects, :method, :pool | |
def thread | |
Thread.new { process_objects } | |
end | |
def process_objects | |
while object = @queue.pop(true) | |
object_description = object.inspect | |
begin | |
puts "Executing: #{object_description}##{method}" | |
object.send(method) | |
rescue StandardError => exception | |
Rollbar.error(exception) | |
end | |
end | |
rescue ThreadError | |
true | |
ensure | |
ActiveRecord::Base.clear_active_connections! | |
end | |
def queue | |
objects_queue = Queue.new | |
objects.each { |obj| objects_queue << obj } | |
objects_queue | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment