SHARE
TWEET

Untitled

a guest Aug 24th, 2019 80 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. class ThreadPool
  2.   def self.execute(objects:, method:, pool: 5)
  3.     new(objects: objects, method: method, pool: pool).execute
  4.   end
  5.  
  6.   def initialize(objects:, method:, pool:)
  7.     @objects = objects
  8.     @method = method
  9.     @pool = pool
  10.     @queue = queue
  11.   end
  12.  
  13.   def execute
  14.     (0...pool).map { thread }.map(&:join)
  15.   end
  16.  
  17.   private
  18.  
  19.   attr_reader :objects, :method, :pool
  20.  
  21.   def thread
  22.     Thread.new { process_objects }
  23.   end
  24.  
  25.   def process_objects
  26.     while object = @queue.pop(true)
  27.       object_description = object.inspect
  28.       begin
  29.         puts "Executing: #{object_description}##{method}"
  30.         object.send(method)
  31.       rescue StandardError => exception
  32.         Rollbar.error(exception)
  33.       end
  34.     end
  35.   rescue ThreadError
  36.     true
  37.   ensure
  38.     ActiveRecord::Base.clear_active_connections!
  39.   end
  40.  
  41.   def queue
  42.     objects_queue = Queue.new
  43.     objects.each { |obj| objects_queue << obj }
  44.     objects_queue
  45.   end
  46. end
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top