map中的Ruby并行处理

map中的Ruby并行处理,ruby,process,parallel-processing,Ruby,Process,Parallel Processing,请帮帮我 如何在两个过程中实现类似于数组的map的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

请帮帮我

如何在两个过程中实现类似于数组的map的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"
类数组
def pmap
out=[]
每个都有|

出获得绝对2个叉子

你不一定需要RPC。马歇尔+管道通常会工作

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
类数组
def pmap
第一个,最后一个=self[0..(self.length/2)],self[(self.length/2+1)…-1]
管道=[first,last].map do |数组|
读、写=IO.pipe
叉子
阅读。关闭
消息=[]
数组。每个do |项|

消息获得绝对2个叉子

你不一定需要RPC。马歇尔+管道通常会工作

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
类数组
def pmap
第一个,最后一个=self[0..(self.length/2)],self[(self.length/2+1)…-1]
管道=[first,last].map do |数组|
读、写=IO.pipe
叉子
阅读。关闭
消息=[]
数组。每个do |项|
消息试试宝石

试试宝石


谷歌的第一个匹配:,第二个:你查过了吗?是的。但是它的代码使用线程。我要求Process.fork实现为什么必须是Process.fork?你在做测验吗?这是要求吗?如果是这样的话,你不是应该自己想出答案吗?第一个匹配是谷歌:,第二个匹配是:你查过了吗?是的。但是它的代码使用线程。我要求Process.fork实现为什么必须是Process.fork?你在做测验吗?这是要求吗?如果是这样的话,你不是应该自己想出答案吗?谢谢你的回答。但是我发现Process.fork实现不在thread中,那么您将需要大量的RPC帮助。这不是小事,这是一块很聪明的宝石。很好的发现。谢谢你的回答。但是我发现Process.fork实现不在thread中,那么您将需要大量的RPC帮助。这不是小事,这是一块很聪明的宝石。很好的发现。