如何管理红宝石线程,使它们完成所有工作? [英] How do I manage ruby threads so they finish all their work?

查看:64
本文介绍了如何管理红宝石线程,使它们完成所有工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个可以划分为独立单元的计算,而现在我要处理的方法是创建固定数量的线程,然后交出每个线程要完成的工作.因此,在伪代码中,这就是它的样子

I have a computation that can be divided into independent units and the way I'm dealing with it now is by creating a fixed number of threads and then handing off chunks of work to be done in each thread. So in pseudo code here's what it looks like

# main thread
work_units.take(10).each {|work_unit| spawn_thread_for work_unit}

def spawn_thread_for(work)
  Thread.new do
    do_some work
    more_work = work_units.pop
    spawn_thread_for more_work unless more_work.nil?
  end
end

基本上,一旦创建了初始数量的线程,每个线程都会做一些工作,然后继续从工作堆栈中取出要完成的工作,直到一无所获.当我在irb中运行内容时,一切都正常,但是当我使用解释器执行脚本时,效果却不尽人意.我不确定如何让主线程等待所有工作完成.有没有办法做到这一点,或者我是否坚持在主线程中执行sleep 10 until work_units.empty?

Basically once the initial number of threads is created each one does some work and then keeps taking stuff to be done from the work stack until nothing is left. Everything works fine when I run things in irb but when I execute the script using the interpreter things don't work out so well. I'm not sure how to make the main thread wait until all the work is finished. Is there a nice way of doing this or am I stuck with executing sleep 10 until work_units.empty? in the main thread

推荐答案

如果修改spawn_thread_for以保存对创建的Thread的引用,则可以在线程上调用Thread#join以等待完成: /p>

If you modify spawn_thread_for to save a reference to your created Thread, then you can call Thread#join on the thread to wait for completion:

x = Thread.new { sleep 0.1; print "x"; print "y"; print "z" }
a = Thread.new { print "a"; print "b"; sleep 0.2; print "c" }
x.join # Let the threads finish before
a.join # main thread exits...

产生:

abxyzc

(从ri Thread.new文档中窃取.有关更多详细信息,请参见ri Thread.join文档.)

(Stolen from the ri Thread.new documentation. See the ri Thread.join documentation for some more details.)

因此,如果修改spawn_thread_for来保存线程引用,则可以将它们全部加入:

So, if you amend spawn_thread_for to save the Thread references, you can join on them all:

(未经测试,但应具有味道)

(Untested, but ought to give the flavor)

# main thread
work_units = Queue.new # and fill the queue...

threads = []
10.downto(1) do
  threads << Thread.new do
    loop do
      w = work_units.pop
      Thread::exit() if w.nil?
      do_some_work(w)
    end
  end
end

# main thread continues while work threads devour work

threads.each(&:join)

这篇关于如何管理红宝石线程,使它们完成所有工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆