LoginSignup
4

More than 5 years have passed since last update.

RubyでWorkpile

Posted at
require 'thread'

class Workpile
  def initialize(num_workers)
    raise ArgumentError, 'Require at least 2 workers' if num_workers < 2
    @queue = Queue.new
    @workers = []
    num_workers.times do
      @workers << Thread.new{ loop{@queue.pop.call} }
    end

    ObjectSpace.define_finalizer(self, proc{@workers.each{|w| w.exit}})
  end

  def push(&block)
    @queue.push block
    @workers.each{|w| w.run} 
  end
end
work = Workpile.new 10

work.push do
  # 処理1
end

work.push do
  # 処理2
end

...

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4