[英]Counter for parallel processes in Ruby
我有使用并行gem在不同进程之间分配工作的代码。
Parallel.map(list, :in_processes=>4) do |item|
if item.name == "A"
puts "A"
else
puts "B"
end
end
为了获得A和B的确切次数,在进程之间共享计数器的最佳方法是什么?
接收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不需要显式的return关键字,但我将其放置以避免任何误解。)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.