简体   繁体   English

Ruby多线程问题

[英]Ruby multithreading questions

I've started looking into multi-threading in Ruby. 我开始研究Ruby中的多线程。

So basically, I want to create a few threads, and have them all execute, but not display any of the output until the thread has successfully completed. 所以基本上,我想创建一些线程,让它们全部执行,但是在线程成功完成之前不显示任何输出。

Example: 例:

#!/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"

The first Hello_1 / Hello_2 execute immediately. 第一个Hello_1 / Hello_2立即执行。 I wouldn't want any of the output to show until the thread has successfully completed. 在线程成功完成之前,我不希望显示任何输出。

Because puts prints to a single output stream (sysout) you can't use it if you want to capture the output each thread. 因为将print打印到单个输出流(sysout),如果要捕获每个线程的输出,则无法使用它。

You will have to use separate buffered stream for each thread, write to that in each thread, and then dump them to sysout when the thread terminates to see the output. 您必须为每个线程使用单独的缓冲流,在每个线程中写入,然后在线程终止时将它们转储到sysout以查看输出。

Here is an example of a thread: 这是一个线程的例子:

t = Thread.new() do
  io = StringIO.new
  io << "mary"
  io.puts "fred"
  io.puts "fred"
  puts io.string
end

You will have to pass io to every method in the thread. 您必须将io传递给线程中的每个方法。

or have a look at this for creating a module that redirects stdout for a thread. 或者看看这个用于创建重定向线程的stdout的模块。

But in each thread that your start wrap your code with: 但是在你开始用你的代码包装的每个线程中:

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

You can share a buffer but you should 'synchronize' access to it: 您可以共享缓冲区,但您应该“同步”访问它:

buffer = ""
lock = Mutex.new

t1 = Thread.new {
lock.synchronize{buffer << "Hello_1\n"}
sleep(5)
lock.synchronize{buffer << "Hello_1 after 5 seconds of  sleep\n"}
}

t2 = Thread.new {
lock.synchronize{buffer << "Hello_2\n"}
sleep(5)
lock.synchronize{buffer << "Hello_2 after 5 seconds of  sleep\n"}
}

t1.join
t2.join

puts buffer

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM