我有这段代码:
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"