我有这个代码使用并行gem来分割不同进程之间的工作。
Parallel.map(list, :in_processes=>4) do |item|
if item.name == "A"
puts "A"
else
puts "B"
end
end
为了获得A和B的确切次数,在进程之间共享计数器的最佳方法是什么?
答案 0 :(得分:1)
接收Parallel的返回值(每次迭代返回值的数组),并使用Array#count方法。
list = ["A","B","A","B","A","B","A","B","A","B"]
result = Parallel.map(list, :in_processes=>4) do |item|
if item == "A"
puts "Got A"
return "A"
else
puts "Got B"
return "B"
end
end
result # Array of "A" and "B" like ["A","B","A","A","B","B","A","A","B","B"]
# Now, you can do whatever you want with the result array.
count_a = result.count("A") # 5
count_b = result.count("B") # 5
(Ruby不需要显式返回关键字,但我这样做是为了避免任何误解。)