Ruby多线程问题

awo*_*ojo 3 ruby multithreading

我开始研究Ruby中的多线程.

所以基本上,我想创建一些线程,让它们全部执行,但是在线程成功完成之前不显示任何输出.

例:

#!/usr/bin/env ruby

t1 = Thread.new {
puts "Hello_1"
sleep(5)
puts "Hello_1 after 5 seconds of  sleep"
}

t2 = Thread.new {
puts "Hello_2"
sleep(5)
puts "Hello_2 after 5 seconds of  sleep"
}

t1.join
t2.join

puts "Hello_3"
sleep(5)
puts "Hello_3 after 5 seconds of  sleep"
Run Code Online (Sandbox Code Playgroud)

第一个Hello_1/Hello_2立即执行.在线程成功完成之前,我不希望显示任何输出.

gri*_*llp 6

因为将print打印到单个输出流(sysout),如果要捕获每个线程的输出,则无法使用它.

您必须为每个线程使用单独的缓冲流,在每个线程中写入,然后在线程终止时将它们转储到sysout以查看输出.

这是一个线程的例子:

t = Thread.new() do
  io = StringIO.new
  io << "mary"
  io.puts "fred"
  io.puts "fred"
  puts io.string
end
Run Code Online (Sandbox Code Playgroud)

您必须将io传递给线程中的每个方法.

或者看看这个用于创建重定向线程的stdout的模块.

但是在你开始用你的代码包装的每个线程中:

Thread.start do
  # capture the STDOUT by storing a StringIO in the thread space
  Thread.current[:stdout] = StringIO.new
  # Do your stuff.. print using puts
  puts 'redirected to StringIO'
  # print everything before we exit
  STDIO.puts Thread.current[:stdout].string
end.join
Run Code Online (Sandbox Code Playgroud)