Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/multithreading/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
确保大量线程在Ruby中完成的最简单方法是什么?_Ruby_Multithreading - Fatal编程技术网

确保大量线程在Ruby中完成的最简单方法是什么?

确保大量线程在Ruby中完成的最简单方法是什么?,ruby,multithreading,Ruby,Multithreading,我正在创建很多线程: (1..255).each do |n| Thread.new do sleep(10) # does a lot of work end end # at this point I need to make sure all the threads completed 我希望我可以将每个线程添加到线程组,并调用类似的函数,直到线程组上的所有线程都完成。但是我在Ruby文档中没有看到任何明显的东西 我是否必须将每个线程添加到一个数组中,然后遍历调用线程的每

我正在创建很多线程:

(1..255).each do |n|
  Thread.new do
    sleep(10) # does a lot of work
  end
end
# at this point I need to make sure all the threads completed
我希望我可以将每个线程添加到
线程组
,并调用类似
的函数,直到
线程组上的所有线程都完成
。但是我在Ruby文档中没有看到任何明显的东西


我是否必须将每个线程添加到一个数组中,然后遍历调用
线程的每个线程。join
?对于这样一个极其常见的用例,必须有一种更简单的方法

threads = (1..255).map do |n|
  Thread.new do
    sleep(10) # does a lot of work
  end
end
threads.each do |thread|
  thread.join
end
使用ThreadGroup#列表 如果使用将线程分配给ThreadGroup,则可以将线程或其他线程方法映射到该方法返回的组的每个成员上。例如:

thread_group = ThreadGroup.new
255.times do
  thread_group.add Thread.new { sleep 10 }
end
thread_group.list.map &:join

这将只连接属于thread_group的线程,而不是ThreadGroup::Default。

“是否必须将每个线程添加到数组中,然后迭代调用thread.join的每个线程”-是。这通常是您处理它的方式,而不考虑语言。
threads.each&:join