2

Help me plz

How i can implement method pmap for Array like map but in two process

I have code

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"

In result i must get 3 second for benchmark

3
  • 1
    first match in google: github.com/bruceadams/pmap, second: stackoverflow.com/questions/5019247/… did you check them? Commented Apr 15, 2013 at 18:52
  • 1
    Yes. But its code use Thread. I ask for Process.fork implimentation Commented Apr 15, 2013 at 19:00
  • 2
    Why does it have to be Process.fork? Are you doing a quiz and that's the requirement? If so, aren't you supposed to come up with the answer yourself? Commented Apr 15, 2013 at 19:12

2 Answers 2

3

To get absolutely 2 forks

You don't absolutely need RPC. Marshal + Pipe should usually work.

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

Edit

Now using fork

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks for answer. But i find Process.fork implimentaion not in Thread
Then you'll need a heavy helping of RPC. This is not trivial.
That's quite a clever gem. Nice find.
3

Try the parallel gem.

require 'parallel'

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.