我有以下代码要阻止,直到所有线程完成(Gist):
ThreadsWait.all_waits(*threads)
在这里设置超时的最简单方法是什么,即如果线程在例如 3 秒后仍在运行,则杀死它们?
Thread#join 接受一个参数,之后它将超时。试试这个,例如:
5.times.map do |i|
Thread.new do
1_000_000_000.times { |i| i } # takes more than a second
puts "Finished" # will never print
end
end.each { |t| t.join(1) } # times out after a second
p 'stuff I want to execute after finishing the threads' # will print
如果您在加入之前有一些事情想要执行,您可以执行以下操作:
5.times.map do |i|
Thread.new do
1_000_000_000.times { |i| i } # takes more than a second
puts "Finished" # will never print
end
end.each do |thread|
puts 'Stuff I want to do before join' # Will print, multiple times
thread.join(1)
end