4
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

RubyでWorkpile

4
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

...
4
4
0

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
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?