ruby多处理-调用函数

ruby多处理-调用函数,ruby,parallel-processing,multiprocessing,Ruby,Parallel Processing,Multiprocessing,我试图将数组传递给函数,并对数组中的每个成员并行运行函数,而不是迭代这些成员。实现这一目标的最佳方式是什么?我成功地使用了process.spawn,但这需要打开一个新的shell。有什么想法吗 谢谢 您可以使用线程(请参阅) 例如: threads = [] your_array.each do |item| threads << Thread.new do # do operation on item. Each one is handled in a new thr

我试图将数组传递给函数,并对数组中的每个成员并行运行函数,而不是迭代这些成员。实现这一目标的最佳方式是什么?我成功地使用了process.spawn,但这需要打开一个新的shell。有什么想法吗


谢谢

您可以使用
线程
(请参阅)

例如:

threads = []
your_array.each do |item|
  threads << Thread.new do
    # do operation on item. Each one is handled in a new thread
  end
end
threads.map(&:join)  # wait for all threads to finish
threads=[]
您的_数组。每个do|项|
线程你可以让你成为红宝石。这提供了对任务进行分叉(多个进程)或线程(多个线程)的选项

如果您希望通过线程实现并行执行,请使用(我们可以打开的线程数量受rails应用程序可用连接的限制):

否则,将使用多个进程实现并行执行(我们可以打开的分支数量受运行应用程序的服务中可用资源的限制):


gem的文档是

我不会为每个数组创建新线程。我会为系统上的每个处理器创建一个(如果你想表现好的话,可能会创建更少的处理器),然后在它们之间分配工作

number_of_threads = 4 
items_per_thread  = work_items_array.length.fdiv(number_of_threads).ceil
work_items.each_slice(items_per_thread) do |items|
  Thread.new do
    items.each do |item|
      process_item(item)
    end 
  end
end
如果所有项目的执行时间都接近同一时间,则此方法效果良好。如果他们不这样做,那么您可能会遇到这样一种情况,即一个线程在另一个线程之前完成很长时间。在这种情况下,您可能希望创建一个项目队列,并让每个线程从队列中提取一个项目来处理。您将需要一个线程安全的队列实现,如Ruby提供的

比如:

queue = Queue.new
work_items.each { |item| queue << item }
number_of_threads.times do |i|
  Thread.new do 
    begin 
      while item=queue.pop(true) do
        process_item(item)          
      end  
    rescue ThreadError
      # thread is empty 
    end
  end 
end   
queue=queue.new
工作项。每个{项|队列
number_of_threads = 4 
items_per_thread  = work_items_array.length.fdiv(number_of_threads).ceil
work_items.each_slice(items_per_thread) do |items|
  Thread.new do
    items.each do |item|
      process_item(item)
    end 
  end
end
queue = Queue.new
work_items.each { |item| queue << item }
number_of_threads.times do |i|
  Thread.new do 
    begin 
      while item=queue.pop(true) do
        process_item(item)          
      end  
    rescue ThreadError
      # thread is empty 
    end
  end 
end