Module: Enumerable

Defined in:
lib/parallel_run.rb

Instance Method Summary collapse

Instance Method Details

#in_groups(number, fill_with = nil) ⇒ Object



85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
# File 'lib/parallel_run.rb', line 85

def in_groups(number, fill_with = nil)
  # size / number gives minor group size;
  # size % number gives how many objects need extra accomodation;
  # each group hold either division or division + 1 items.
  division = size / number
  modulo = size % number

  # create a new array avoiding dup
  groups = []
  start = 0

  number.times do |index|
    length = division + (modulo > 0 && modulo > index ? 1 : 0)
    padding = fill_with != false &&
      modulo > 0 && length == division ? 1 : 0
    groups << slice(start, length).concat([fill_with] * padding)
    start += length
  end

  if block_given?
    groups.each{|g| yield(g) }
  else
    groups
  end
end

#peach(workers = nil, &b) ⇒ Object



111
112
113
114
115
116
117
118
119
120
121
122
# File 'lib/parallel_run.rb', line 111

def peach(workers = nil, &b)
  workers ||= count

  threads = []
  in_groups(workers, false).each do |slice|
    threads << Thread.new(slice) do |thread_slice|
      thread_slice.each{|elt| yield elt}
    end
  end
  threads.each{|t| t.join }
  self
end