ruby - 如何阻止主线程退出?

标签 ruby multithreading concurrency

我有这个代码:

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/

相关文章:

java - 在 Android 中,如何让 Activity 在跳到下一个 Activity 之前等待?

java - future 超时和IO超时

multithreading - 关于多线程、并发和并行

multithreading - std::condition_variable::wait 访问冲突

html - 在 HAML 中的链接中嵌套链接时遇到问题

c++ - 在 openmp 中使用不同线程组装 vector 时缩放比例不佳

ruby - 我可以使用指定名称创建类的实例吗?

go - 如何同时搜索一大片 maps[string]string

ruby - 使用 Ruby 调用 shell 脚本退出代码总是返回 0

ruby-on-rails - 每当 cron 不触发备份时