我有这个代码:
5.times do |num|
puts "Spawning thread ##{num}"
Thread.new {
fun
puts "Thread ##{num} is done"
}
end
fun
需要很长时间才能完成,因此主线程已经退出。我知道我可以使用 sleep
,但如果 fun
花费的时间比预期长怎么办?如何无限期地暂停主线程而不阻塞?
最佳答案
如 documentation for Thread
中所述,你必须join
线程:
def fun
sleep 2
end
threads = []
5.times do |num|
puts "Spawning thread ##{num}"
threads << Thread.new {
fun
puts "Thread ##{num} is done"
}
end
threads.each(&:join)
输出:
Spawning thread #0
Spawning thread #1
Spawning thread #2
Spawning thread #3
Spawning thread #4
2 秒后:
Thread #4 is done
Thread #0 is done
Thread #1 is done
Thread #3 is done
Thread #2 is done
关于ruby - 如何阻止主线程退出?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33961133/