6

我有这段代码:

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

我期望看到“开始”,然后是“来自线程的问候”,然后我可以输入会回显给我的输入。相反,我得到“Start”和“Hello from thread”,然后程序退出。

从文档中exit

终止 thr 并安排另一个线程运行。如果这个线程已经被标记为被杀死,exit 返回这个线程。如果这是主线程或最后一个线程,则退出该进程。

但我以为我产生了一个新线程?为什么它退出我的主进程?

4

1 回答 1

9

您正在查看Thread#exit文档。killKernel#exit终止 Ruby 脚本。

puts "Start"
loop do
    Thread.start do
        puts "Hello from thread"
        Thread.exit
    end
    text = gets
    puts "#{text}"
end
puts "Done"
于 2013-09-04T03:23:04.467 回答