Skip to content

Instantly share code, notes, and snippets.

@squarism
Last active August 29, 2015 14:00
Show Gist options
  • Save squarism/11184993 to your computer and use it in GitHub Desktop.
Save squarism/11184993 to your computer and use it in GitHub Desktop.
ruby pmap
# Ruby pmap, like Scala's pmap method.
# ------------------------------------
# modified from t-a-w.blogspot.com
require 'thread'
module Enumerable
def pmap(n)
todo = Queue.new
each {|x| todo << [x] }
n.times { todo << nil }
threads = (1..n).map do
Thread.new do
while x = todo.pop
yield(x[0])
end
end
end
threads.each {|t| t.join }
end
end
# -- Examples
# -- Notice that if you increase the concurrency in pmap(3)
# -- the total time to run this program decreases.
#
# class Person
# attr_accessor :name
# end
# peeps = [
# Person.new.tap {|p| p.name = "Joe" },
# Person.new.tap {|p| p.name = "Jane" },
# Person.new.tap {|p| p.name = "David" }
# ]
#
# peeps.pmap(3) do |person|
# puts "found david" if person.name == "David"
# sleep 1
# end
#
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment