我正在尝试处理一个数组,每个元素都需要花费合理的时间来处理(≈30 分钟)。为了加快进程,我想使用 fork
,这样元素就可以在不同的进程中并行处理。但是我的数组有大约 1000 个元素,我不想一次制作 1000 个 fork 。
我可以分批 n 执行 fork
,然后等到它们都用 Process.waitall
完成,但是有没有办法我可以在上一个流程结束后立即开始一个新流程吗?
最佳答案
可以通过以下方式解决:
# assign maximum number of processes
counter = @max_processes
# when a child process ends increase the counter of available processes
Signal.trap("CLD") { counter += 1 }
your_array.each do |element|
# wait for a child process to end if there are no more "available processes"
Process.wait if counter <= 0
# before launching a process decrease the "available processes" counter
counter -= 1
fork {
# do something with an element
}
end
一个更简单的选择是将数组拆分为子数组并并行运行它们:
your_array.each_slice(@max_processes) do |elements|
elements.each do |element|
fork {
# do something with an element
}
end
Process.waitall
end
关于ruby - 限制 fork 进程的数量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35387024/