Ruby ThreadsWait 超时
Ruby ThreadsWait timeout
我有以下代码要阻塞,直到所有线程都完成 (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
我有以下代码要阻塞,直到所有线程都完成 (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