使用 ruby 多线程处理并行任务时,某些线程因为任务执行出现异常(我想可能是挂起了),使得进程最后成了垃圾进程。查 ruby 手册发现Thread#join
方法还有个参数,如果加个参数会设置为线程对象的超时时间,过时后自动退出。
写了两个测试:
(1)
test_thread = Thread.new {sleep 10; puts "Thread completed" }
test_thread.join(3)
puts "------------END----------------"
在 thread 的 join 加上参数后三秒线程退出了
(2)根据我的任务场景写了个测试
threads = []
10.times do |i|
threads << Thread.new do
sleep i + 1
puts "This is the #{i} thread!"
end
end
puts "All threads create completed!"
threads.each {|t| t.join(3) }
puts "------------END----------------"
结果很奇怪:
All threads create completed!
This is the 0 thread!
This is the 1 thread!
This is the 2 thread!
This is the 3 thread!
This is the 4 thread!
This is the 5 thread!
This is the 6 thread!
This is the 7 thread!
This is the 8 thread!
This is the 9 thread!
------------END----------------
按照文档应该输出到 This is the 2 thread!
后其他进程就该退出了,但是十个都执行完了,求解!
ps:用多线程执行的单个任务一般不会超过 10s,但是有可能出现无响应的状态,本来想让线程执行超时设置到 30s,这样能保证主进程完毕后退出,但有可能是线程执行异常的问题,过很长时间后发现任务机器上残留几个 ruby 进程,每次都要手动清理。可能是多线程理解不到位,求大神帮忙啊!