Sin*_*ion 2 ruby multithreading
我正在尝试了解 Ruby 多线程,但它似乎很混乱。这是我尝试过的几个例子:
Thread.new do
puts "thread"
end
puts "main"
Run Code Online (Sandbox Code Playgroud)
thread = Thread.new do
puts "thread"
end
sleep while thread.alive?
puts "main"
Run Code Online (Sandbox Code Playgroud)
thread = Thread.new do
puts "thread"
end
puts thread.status while thread.alive?
puts "main"
Run Code Online (Sandbox Code Playgroud)
以马茨的名义在这里发生了什么?!
线程永远不会被执行并且程序结束
Thread.new do
puts "thread"
end
puts "main"
Run Code Online (Sandbox Code Playgroud)
线程并行运行。主 Ruby 进程不会自动等待所有线程完成后再退出。
你缺少的是join. 这会一直等到线程完成。
thread = Thread.new do
puts "thread"
end
puts "main"
thread.join
Run Code Online (Sandbox Code Playgroud)
线程被执行但永不终止
thread = Thread.new do
puts "thread"
end
sleep while thread.alive?
puts "main"
Run Code Online (Sandbox Code Playgroud)
sleep没有争论永远沉睡。给它短暂的睡眠时间,它会起作用。
thread = Thread.new do
puts "thread"
end
sleep(0.1) while thread.alive?
puts "main"
Run Code Online (Sandbox Code Playgroud)
一切都出乎意料地按预期工作:
thread = Thread.new do
puts "thread"
end
puts thread.status while thread.alive?
puts "main"
Run Code Online (Sandbox Code Playgroud)
既然您不会永远沉睡,它就会按预期工作。