Ruby多线程问题 [英] Ruby multithreading questions
问题描述
我已经开始研究Ruby中的多线程.
I've started looking into multi-threading in 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.
示例:
#!/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"
第一个Hello_1/Hello_2立即执行.在线程成功完成之前,我不希望显示任何输出.
The first Hello_1 / Hello_2 execute immediately. I wouldn't want any of the output to show until the thread has successfully completed.
推荐答案
由于将打印输出到单个输出流(sysout),因此如果要捕获每个线程的输出,则不能使用它.
Because puts prints to a single output stream (sysout) you can't use it if you want to capture the output each thread.
您将必须为每个线程使用单独的缓冲流,在每个线程中写入该缓冲流,然后在线程终止以将其转储到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.
以下是线程的示例:
t = Thread.new() do
io = StringIO.new
io << "mary"
io.puts "fred"
io.puts "fred"
puts io.string
end
您将必须将io传递给线程中的每个方法.
You will have to pass io to every method in the thread.
or have a look at this for creating a module that redirects stdout for a thread.
但是在您开始使用的每个线程中,您的代码都包含以下内容:
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
这篇关于Ruby多线程问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!