代码之家  ›  专栏  ›  技术社区  ›  vinibrsl

如何只等待数组中的第一个线程在Ruby中完成?

  •  1
  • vinibrsl  · 技术社区  · 8 年前

    在Ruby中,可以使用 Thread#join :

    threads = []
    
    threads << Thread.new { sleep 1 }
    threads << Thread.new { sleep 5 }
    threads << Thread.new { sleep 2 }
    
    # waiting for all work to finish
    threads.each(&:join)
    

    在Ruby中有简单的方法或者内置的方法吗?

    1 回复  |  直到 8 年前
        1
  •  4
  •   matthewd    8 年前

    对于线程安全的方法,可以使用队列来等待多个线程中的某个线程发生事件。

    queue = Queue.new
    threads = []
    
    threads << Thread.new { sleep 2; queue.push(nil) }
    threads << Thread.new { sleep 50; queue.push(nil) }
    threads << Thread.new { sleep 20; queue.push(nil) }
    
    # wait for one
    queue.pop
    
    # clean up the rest
    threads.each(&:kill).each(&:join)