【问题标题】:Ruby 1.9.3-p140 - Using Thread - how to wait for all results to come out from threads?Ruby 1.9.3-p140 - 使用线程 - 如何等待所有结果从线程中出来?
【发布时间】:2012-08-22 13:08:47
【问题描述】:

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

如何在下面的代码中做到这一点?

    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 循环,程序会在线程完成之前完成。

【问题讨论】:

  • counter = 1000 如代码顶部所述。
  • 抱歉,没有 100% 关注。别介意我无关紧要的评论。

标签: ruby multithreading coding-style mutex fibers


【解决方案1】:

要让父级等待子级完成,您可以使用 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 }

【讨论】:

  • 我应该在 counter.time 循环中添加 thr 吗?然后我为每个线程使用 thr.join out 边?
  • 您需要加入您创建的每个线程。因此,将赋值添加到循环内的 thr 变量,然后在退出每个循环迭代之前对其调用 join。
  • 我试过这个: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 thr.join end Now ,代码不是运行多线程,而是再次序列化进程。我必须等待每个线程休眠 1 秒,而不是让所有线程同时执行。
  • 啊,是的,糟糕,您需要在加入之前创建所有线程。与其立即调用 join,不如在创建线程的循环之前创建一个数组,并将每个新创建的线程添加到数组中。退出循环后,加入数组中的每个线程。
【解决方案2】:

您需要保留对线程的引用,以便“加入”它们。比如:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-11-03
    • 1970-01-01
    • 2014-06-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多