如何阻止主线程退出?

时间:2015-11-27 16:06:04

标签: ruby multithreading concurrency

我有这段代码:

5.times do |num|
    puts "Spawning thread ##{num}"
    Thread.new {
        fun
        puts "Thread ##{num} is done"
    }
end

fun需要很长时间才能完成,因此主线程已经退出。我知道我可以使用sleep,但如果fun花费的时间比预期的要长呢?如何在不阻塞的情况下无限期地暂停主线程?

1 个答案:

答案 0 :(得分:2)

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