【发布时间】:2020-08-17 23:44:07
【问题描述】:
我正在尝试使用 Ruby 来理解流程。我正在从我的父进程创建 4 个子进程。主进程首先写入文件,然后创建子进程,每个子进程都写入同一个文件:
require 'csv'
a = [1, 2, 3, 4]
CSV.open("temp_and_cases_batch_parallel.csv", "ab") do |target_file|
target_file << ["hello from parent process #{Process.pid}"]
a.each do |num|
pid = Process.fork do
target_file << ["hello from child Process #{Process.pid}"]
end
puts "parent, pid #{Process.pid}, waiting on child pid #{pid}"
end
end
Process.wait
puts "parent exiting"
我期望的文件输出
hello from parent process 3336
hello from child Process 3350
hello from child Process 3351
hello from child Process 3349
hello from child Process 3352
我实际得到的文件输出:
hello from parent process 3336
hello from parent process 3336
hello from child Process 3350
hello from parent process 3336
hello from child Process 3351
hello from parent process 3336
hello from child Process 3349
hello from parent process 3336
hello from child Process 3352
似乎来自父进程的插入重新运行了 5 次。这怎么可能?这是怎么回事?
【问题讨论】:
-
什么版本的 ruby 以及你的 csv 的内容是什么?
-
脚本开始时 csv 为空,我使用的是 ruby 2.6.3
标签: ruby csv parallel-processing process