Module: Enumerable

Defined in:
lib/peach.rb

Overview

monkey patch Enumerable by reopening it. Enumerable.send(:include, Peach) doesn’t seem to work as it should.

Instance Method Summary collapse

Instance Method Details

#_peach_run(pool = nil, &b) ⇒ Object



4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
# File 'lib/peach.rb', line 4

def _peach_run(pool = nil, &b)
  pool ||= $peach_default_threads || count
  pool = 1 unless pool >= 1
  div = (count/pool).to_i # should already be integer
  div = 1 unless div >= 1 # each thread better do something!

  threads = []
  each_slice(div).with_index do |slice, idx|
    threads << Thread.new(slice) do |thread_slice|
      yield thread_slice, idx, div
    end
  end
  threads.each{|t| t.join }
  self
end

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



20
21
22
23
24
# File 'lib/peach.rb', line 20

def peach(pool = nil, &b)
  _peach_run(pool) do |thread_slice, idx, div|
    thread_slice.each{|elt| yield elt}
  end
end

#pmap(pool = nil, &b) ⇒ Object



26
27
28
29
30
31
32
33
34
35
36
37
38
39
# File 'lib/peach.rb', line 26

def pmap(pool = nil, &b)
  result = Array.new(count)
  lock = Mutex.new

  _peach_run(pool) do |thread_slice, idx, div|
    thread_slice.each_with_index do |elt, offset| 
      local_result = yield elt
      lock.synchronize do
        result[(idx*div)+offset] = local_result
      end
    end
  end
  result
end

#pselect(pool = nil, &b) ⇒ Object



41
42
43
44
45
46
47
48
49
50
51
52
53
# File 'lib/peach.rb', line 41

def pselect(pool = nil, &b)
  results, result = [],[]
  lock = Mutex.new

  _peach_run(pool) do |thread_slice, idx, div|
    local_result = thread_slice.select(&b)
    lock.synchronize do
      results[idx] = local_result
    end
  end
  results.each {|x| result += x if x}
  result
end