Ruby 1.9.3-p140 - 使用线程 - 如何等待线程中的所有结果?

时间:2012-08-22 13:08:47

标签: ruby multithreading coding-style mutex fibers

我试图想办法在主线程完成之前等待所有线程执行的好方法。

我如何在以下代码中执行此操作?

    threads = []

    counter = 1000

    lines = 0

    counter.times do |i|
      puts "This is index number #{i}."
    end

    puts "You've just seen the normal printing and serial programming.\n\n"

    counter.times do |i|
      Thread.new do
        some_number = Random.rand(counter)
        sleep 1
        puts "I'm thread number #{i}. My random number is #{some_number}.\n"
        lines += 1
      end
    end

    messaged = false
    while lines < 1000
      puts "\nWaiting to finish.\n" unless messaged
      print '.'
      puts "\n" if lines == 1000
      messaged = true
    end

    puts "\nI've printed #{lines} lines.\n"
    puts "This is end of the program."

该程序将I&#m; m号码设为XXX。我的随机数是YYY,与while循环中的点几乎在主线程的末尾混合。如果我不使用while循环,程序将在线程完成之前完成。

2 个答案:

答案 0 :(得分:3)

要让父母等待孩子完成,请使用加入

 threads = []
 counter.times do |i|
    thr = Thread.new do
            some_number = Random.rand(counter)
            sleep 1
            puts "I'm thread number #{i}. My random number is #{some_number}.\n"
            lines += 1
    end
    threads << thr
  end
  threads.each {|thread| thread.join }

答案 1 :(得分:1)

您需要保留对线程的引用,以便您可以加入&#39;他们。类似的东西:

counter.times.map do |i|
  Thread.new do
    # thread code here
  end
end.each{|t| t.join}