微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

为什么退出Ruby线程会杀死我的整个程序?

我有这段代码
puts "Start"
loop do
    Thread.start do
        puts "Hello from thread"
        exit
    end
    text = gets
    puts "#{text}"
end
puts "Done"

我期望看到“开始”后跟“线程中的Hello”,然后我可以输入回复给我的输入.相反,我得到“开始”和“来自线程的Hello”,然后程序退出.

退出文档:

Terminates thr and schedules another thread to be run. If this thread
is already marked to be killed,exit returns the Thread. If this is
the main thread,or the last thread,exits the process.

但我以为我催生了一个新线程?为什么退出我的主要流程?

解决方法

您正在查看 Thread#exit文档. kill是 Kernel#exit,它终止了Ruby脚本.
puts "Start"
loop do
    Thread.start do
        puts "Hello from thread"
        Thread.exit
    end
    text = gets
    puts "#{text}"
end
puts "Done"

原文地址:https://www.jb51.cc/ruby/264645.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐