为什么退出Ruby线程会杀死我的整个程序? [英] Why does exiting a Ruby thread kill my whole program?

查看:83
本文介绍了为什么退出Ruby线程会杀死我的整个程序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这段代码:

puts "Start"
loop do
    Thread.start do
        puts "Hello from thread"
        exit
    end
    text = gets
    puts "#{text}"
end
puts "Done"

我希望看到的是开始",然后是来自线程的Hello",然后我可以输入会回显给我的输入.取而代之的是,我得到开始"和来自线程的问候",然后程序退出.

What I would expect is seeing "Start" followed by "Hello from thread" and then I could enter input that would get echoed back to me. Instead I get "Start" and "Hello from thread" and then the program exits.

摘自exit上的文档:

终止thr并计划另一个线程要运行.如果这个线程 已被标记为已杀死,退出将返回线程.如果是这样 主线程或最后一个线程退出进程.

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.

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

But I thought I spawned a new thread? Why is it exiting my main process?

推荐答案

您正在查看 Thread#exit 文档. kill Kernel#exit 终止Ruby脚本.

You're looking at the Thread#exit documentation. kill is Kernel#exit which terminates the Ruby script.

puts "Start"
loop do
    Thread.start do
        puts "Hello from thread"
        Thread.exit
    end
    text = gets
    puts "#{text}"
end
puts "Done"

这篇关于为什么退出Ruby线程会杀死我的整个程序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆