据我所知,Ruby MRI 1.8.7中的文件写入是完全线程安全的。
示例1 - 完美结果:
File.open("test.txt", "a") { |f|
threads = []
1_000_000.times do |n|
threads << Thread.new do
f << "#{n}content\n"
end
end
threads.each { |t| t.join }
}
例子2-完美的结果(但更慢):
threads = []
100_000.times do |n|
threads << Thread.new do
File.open("test2.txt", "a") { |f|
f << "#{n}content\n"
}
end
end
threads.each { |t| t.join }
那么,我无法构建出一个遇到并发问题的情景,你能吗?
如果有人能够解释一下为什么我还应该在这里使用Mutex,我将不胜感激。
编辑:这是另一个更复杂的示例,它完全正常工作,并且不会显示并发问题:
def complicated(n)
n.to_s(36).to_a.pack("m").strip * 100
end
items = (1..100_000).to_a
threads = []
10_000.times do |thread|
threads << Thread.new do
while item = items.pop
sleep(rand(100) / 1000.0)
File.open("test3.txt", "a") { |f|
f << "#{item} --- #{complicated(item)}\n"
}
end
end
end
threads.each { |t| t.join }
Thread#join
需要在File::open
块内部。请参考此问题的答案以了解为什么以及 JRuby 的结果:https://stackoverflow.com/questions/64352404/writing-to-a-file-from-multiple-threads/ - byteit101