Class: Jparallel

Inherits:
Object
  • Object
show all
Defined in:
lib/jparallel.rb

Instance Method Summary collapse

Constructor Details

#initialize(poolsize) ⇒ Jparallel

Returns a new instance of Jparallel.



6
7
8
# File 'lib/jparallel.rb', line 6

def initialize poolsize
  @pool = Thread.pool poolsize
end

Instance Method Details

#hashmap(input_hash, &block) ⇒ Object



49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
# File 'lib/jparallel.rb', line 49

def hashmap (input_hash, &block)
  output_hash = {}

  input_hash.each_pair do |key, value|
    output_hash[key] = Thread.future @pool do
      begin
        yield(key, value)
      rescue => e
        e
      end
    end
  end

  output_hash.each_pair do |key, value_future|
    output_hash[key] = value_future.value
  end

  output_hash
end

#map(input_array, ops = {}, &block) ⇒ Object



10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
# File 'lib/jparallel.rb', line 10

def map (input_array, ops={}, &block)
  timeout = ops[:timeout]
  output_array = Array.new input_array.length
  start_time = Time.now

  input_array.each_with_index do |item, index|
    output_array[index] = Thread.future @pool do
      if !timeout.nil? &&
          ( Time.now - start_time ) > timeout
        TimeoutError.new("Timed out before item #{index}")
      else
        begin
          yield(item)
        rescue => e
          e
        end
      end
    end
  end

  output_array.map(&:value)
end

#map_with_index(input_array, &block) ⇒ Object



33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
# File 'lib/jparallel.rb', line 33

def map_with_index (input_array, &block)
  output_array = Array.new input_array.size

  input_array.each_with_index do |item, index|
    output_array[index] = Thread.future @pool do
      begin
        yield(item, index)
      rescue => e
        e
      end
    end
  end

  output_array.map(&:value)
end