Skip to content

Instantly share code, notes, and snippets.

@seeker815
Forked from sczizzo/pmap.rb
Created March 17, 2016 09:05
Show Gist options
  • Save seeker815/c54b4b85cc2587d67acb to your computer and use it in GitHub Desktop.
Save seeker815/c54b4b85cc2587d67acb 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