我正在阅读David A. Black的《 The Well-Grounded Rubyist,第三版》。
在线程部分,以下代码段的作者输出与我的系统上显示的内容不同(第14.5节)。
Thread.new do
puts "Starting the thread"
sleep 1
puts "At the end of the thread"
end
puts "Outside the thread"
作者的输出:
Starting the thread
Outside the thread
我的输出仅为:
Outside the thread
然后作者将代码块设置为变量t
并调用t.join
,这将为他提供以下输出:
Starting the thread
Outside the thread
At the end of the thread
但是,我的输出是:
Outside the thread
Starting the thread
At the end of the thread
我想念什么吗?
我正在使用ruby 2.5.1p57(2018-03-29修订版63029)[x86_64-linux-gnu]
答案 0 :(得分:1)
因为主线程在生成的线程开始之前继续执行工作。
1,尝试在puts "Outside the thread"
之前睡0.1
Thread.new do
puts "Starting the thread"
sleep 1
puts "At the end of the thread"
end
sleep 0.1 #let spawned thread start
puts "Outside the thread"
puts "Outside the thread"
之前加入Thread.new do
puts "Starting the thread"
sleep 1
puts "At the end of the thread"
end.join # wait spawned thread finish
puts "Outside the thread"