Class: Chef::ChefFS::Parallelizer::ParallelizedResults

Inherits:
Object
  • Object
show all
Includes:
Enumerable
Defined in:
lib/chef/chef_fs/parallelizer.rb

Instance Method Summary collapse

Constructor Details

#initialize(enumerator, options, &block) ⇒ ParallelizedResults

Returns a new instance of ParallelizedResults.



39
40
41
42
43
44
45
46
47
# File 'lib/chef/chef_fs/parallelizer.rb', line 39

def initialize(enumerator, options, &block)
  @inputs = enumerator.to_a
  @options = options
  @block = block

  @mutex = Mutex.new
  @outputs = []
  @status = []
end

Instance Method Details

#eachObject



49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
# File 'lib/chef/chef_fs/parallelizer.rb', line 49

def each
  next_index = 0
  while true
    # Report any results that already exist
    while @status.length > next_index && ([:finished, :exception].include?(@status[next_index]))
      if @status[next_index] == :finished
        if @options[:flatten]
          @outputs[next_index].each do |entry|
            yield entry
          end
        else
          yield @outputs[next_index]
        end
      else
        raise @outputs[next_index]
      end
      next_index = next_index + 1
    end

    # Pick up a result and process it, if there is one.  This ensures we
    # move forward even if there are *zero* worker threads available.
    if !process_input
      # Exit if we're done.
      if next_index >= @status.length
        break
      else
        # Ruby 1.8 threading sucks.  Wait till we process more things.
        sleep(0.05)
      end
    end
  end
end

#process_inputObject



82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
# File 'lib/chef/chef_fs/parallelizer.rb', line 82

def process_input
  # Grab the next one to process
  index, input = @mutex.synchronize do
    index = @status.length
    if index >= @inputs.length
      return nil
    end
    input = @inputs[index]
    @status[index] = :started
    [ index, input ]
  end

  begin
    @outputs[index] = @block.call(input)
    @status[index] = :finished
  rescue Exception
    @outputs[index] = $!
    @status[index] = :exception
  end
  index
end