Skip to content

Instantly share code, notes, and snippets.

@sczizzo
Created March 7, 2016 15:35
Show Gist options
  • Save sczizzo/f71444959e65dfafd94d to your computer and use it in GitHub Desktop.
Save sczizzo/f71444959e65dfafd94d to your computer and use it in GitHub Desktop.
Simple, plain Ruby implementation of parallel map/each
#!/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