Created
March 7, 2016 15:35
-
-
Save sczizzo/f71444959e65dfafd94d to your computer and use it in GitHub Desktop.
Simple, plain Ruby implementation of parallel map/each
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env ruby | |
require 'thread' | |
Thread.abort_on_exception = true | |
module Enumerable | |
def peach n=nil, &block | |
pmap n, &block | |
self | |
end | |
def pmap n=nil | |
n = size if n.nil? || n > size | |
q = Queue.new | |
each { |i| q.push i } | |
rs = [] | |
ws = Array.new(n).map do | |
Thread.new do | |
loop do | |
begin | |
i = q.pop true | |
rescue ThreadError | |
break | |
end | |
rs << yield(i) | |
end | |
end | |
end | |
ws.map(&:join) | |
rs | |
end | |
end | |
r = (1..5).peach do |i| | |
sleep i | |
puts i | |
end | |
puts r.inspect |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment