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

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

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

最佳答案

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

关于Ruby 1.9.3-p140 - 使用线程 - 如何等待所有结果从线程中出来?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12073892/

相关文章:

ruby - 我如何理解 Ruby 文档?

Python:将传入的串行数据发送到 MySQL

c - Linux 内核线程

java - 扩展类与添加 boolean 参数

c++ - 将 char 绑定(bind)到枚举类型

Ruby - 将具有管道分隔值的数组转换为哈希数组

ruby-on-rails - 错误 : mime-types-data requires Ruby version >= 2. 0

ruby-on-rails - 添加一个浅层资源作为另一个资源的成员

java - 没有 Activity 的 runOnUiThread

c++ - 为什么在 C++ 中使用 = 来初始化原始类型?