2

我试图找出一种在主线程完成之前等待所有线程执行的好方法。

我怎样才能在下面的代码中做到这一点?

    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."

该程序将我的线程号 XXX。我的随机数是 YYY,几乎在主线程结束时与 while 循环中的点混合。如果我不使用 while 循环,程序会在线程完成之前完成。

4

2 回答 2

3

要让父母等待孩子完成,您可以使用 join

 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 }
于 2012-08-22T13:15:17.567 回答
1

您需要保留对线程的引用,以便您可以“加入”它们。就像是:

counter.times.map do |i|
  Thread.new do
    # thread code here
  end
end.each{|t| t.join}
于 2012-08-22T14:08:38.510 回答