Ruby中的Ruby并行流程

时间:2013-04-15 18:32:02

标签: ruby process parallel-processing

帮帮我PLZ

我如何为地图实现方法pmap,但是在两个过程中

我有代码

class Array

  def pmap
    out = []
    each do |e|
      out << yield(e)
    end
    out
  end

end

require 'benchmark'

seconds = Benchmark.realtime do
  [1, 2, 3].pmap do |x|
    sleep x
    puts x**x
  end
end

puts "work #{seconds} seconds"

结果我必须得到3秒的基准

2 个答案:

答案 0 :(得分:3)

绝对获得2 分叉

你并不一定需要RPC。 Marshal + Pipe通常应该有效。

class Array

  def pmap
    first, last = self[0..(self.length/2)], self[(self.length/2+1)..-1]

    pipes = [first, last].map do |array|
      read, write = IO.pipe
      fork do
        read.close
        message = []
        array.each do |item|
          message << yield(item)
        end
        write.write(Marshal.dump message)
        write.close
      end
      write.close
      read
    end

    Process.waitall

    first_out, last_out = pipes.map do |read|
      Marshal.load(read.read)
    end

    first_out + last_out
  end

end

修改

现在使用fork

答案 1 :(得分:2)

尝试parallel gem。

require 'parallel'

class Array
  def pmap(&blk)
    Parallel.map(self, {:in_processes: 3}, &blk)
  end
end