2017-04-06 5 views
0

ruby​​でマルチスレッドを行い、子プロセスの結果を親の配列に格納する方法を知りたいと思います。マルチプロセスRubyとストア変数

処理したい配列には400個の項目があります。

私は2つのソリューションを試しました。

Solution: 1 (http://www.rubydoc.info/gems/parallel-forkmanager/Parallel/ForkManager) 

require forkmanager 

eng = [] 

array = [{'ip' => 12.34.56,'hostname' => ''}, {'ip' => 22.22.22, 'hostname' => ''} 

pm = Parallel::ForkManager.new(20) 
pm.run_on_finish{|pid, exit_code, return_list| 
    eng << return_list 
} 

array.each do |node| 
    pm.start(node) and wait 
    new_node = process(node) #gives a value to hostname 
    pm.finish(0, new_node) 
end 
pm.wait_all_children 
puts eng #expects it to return new node but it returns node. 




Solution 2: (https://github.com/grosser/parallel) 
require 'parallel' 
eng =[] 
array = [{'ip' => 12.34.56,'hostname' => ''}, {'ip' => 22.22.22, 'hostname' => ''} 
Parallel.map(array, in_processes: 20) do |node| 
    new_node = process(node) #gives a value to hostname 
    eng << new_node 
end 
puts eng #expected to provide nodes. returns empty array instead. 

答えて

0

Parallel.mapそれは、配列内の指定された要素に、各ブロックの実行結果を返し、そうあなたは、単に、各ノードの処理結果を取得するには、このような何かを行うことができますという点で非常にEnumerable.map次のように動作します。

eng = Parallel.map(array, in_processes: 20) do |node| 
    process(node) # Return the result of processing `node`. `Parallel.map` will return these results for each node in an array 
end 

puts eng # This will have the expected nodes now 
関連する問題