Sea*_*123 6 ruby multithreading
我有这段代码:
puts "Start"
loop do
Thread.start do
puts "Hello from thread"
exit
end
text = gets
puts "#{text}"
end
puts "Done"
Run Code Online (Sandbox Code Playgroud)
我期望看到"开始"后跟"线程中的Hello",然后我可以输入回复给我的输入.相反,我得到"开始"和"来自线程的Hello",然后程序退出.
从以下文档exit:
终止thr并调度另一个要运行的线程.如果此线程已被标记为被杀死,则exit返回Thread.如果这是主线程或最后一个线程,则退出进程.
但我以为我催生了一个新线程?为什么退出我的主要流程?
你正在查看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"
Run Code Online (Sandbox Code Playgroud)