我尝试了《 Well Grounded Rubyist》一书中的一个示例,该书在我的Ruby 2.0中使用了Ruby 1.9,并获得了不同的结果。取而代之的是:
启动线程
外螺纹
我只得到第二行:
外螺纹
这是代码示例:
Thread.new do
puts "Starting a thread"
sleep 2
puts "At the end of the thread"
end
puts "Outside the thread"
为什么这样?
您可以在此处看到不同的结果:(在线ruby解释器-第一个是ruby 1.9,第二个是ruby 2.0)
如果将其作为可执行文件而不是IRB运行,则还需要使子线程在某些时候加入父线程。否则,当父母做完后,孩子将被杀死。
#!/usr/bin/env ruby
t = Thread.new do
puts "Starting a thread"
sleep 2
puts "At the end of the thread"
nil
end
puts "Outside the thread"
t.join
我无法在笔记本电脑上重现不同的输出:
~/wk $ /usr/bin/ruby --version
ruby 1.8.7 (2012-02-08 patchlevel 358) [universal-darwin11.0]
~/wk $ /usr/local/bin/ruby --version
ruby 2.0.0p247 (2013-06-27 revision 41674) [x86_64-darwin11.4.2]
与t.join
:
~/wk $ /usr/bin/ruby test.rb
Starting a thread
Outside the thread
At the end of the thread
~/wk $ /usr/local/bin/ruby test.rb
Starting a thread
Outside the thread
At the end of the thread
没有t.join
:
~/wk $ /usr/bin/ruby test.rb
Starting a thread
Outside the thread
~/wk $ /usr/local/bin/ruby test.rb
Starting a thread
Outside the thread
我确实在服务器上重现了它们:
~ $ ruby --version
ruby 1.9.3p448 (2013-06-27 revision 41675) [amd64-freebsd9]
与t.join
:
~ $ ruby test.rb
Outside the thread
Starting a thread
At the end of the thread
没有t.join
:
~ $ ruby test.rb
Outside the thread
sleep 1
但是,如果我在脚本的末尾添加内容,则会得到以下内容:
~ $ ruby test.rb
Outside the thread
Starting a thread
因此,methinks可能没有任何外观上的区别,可能只是在外观上的实现细节之外。您只需要加入父母。
另外,当然,您不应该期望“线程外”和“启动线程”有任何特定顺序。两者并行运行,并且不能保证一个发生在另一个之前。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句