aboutsummaryrefslogtreecommitdiff
path: root/vendor/rsync_command/lib/rsync_command/thread_pool.rb
blob: c788ee257463866b3cbde011efa525962d4d08ec (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
require 'thread'

class RsyncCommand
  class ThreadPool
    class << self
      attr_accessor :default_size
    end

    def initialize(size=nil)
      @size = size || ThreadPool.default_size || 10
      @jobs = Queue.new
      @retvals = []
      @pool = Array.new(@size) do |i|
        Thread.new do
          Thread.current[:id] = i
          catch(:exit) do
            loop do
              job, args = @jobs.pop
              @retvals << job.call(*args)
            end
          end
        end
      end
    end
    def schedule(*args, &block)
      @jobs << [block, args]
    end
    def shutdown
      @size.times do
        schedule { throw :exit }
      end
      @pool.map(&:join)
      @retvals
    end
  end
end