Skip to content

Instantly share code, notes, and snippets.

@jdeveloper
Created July 13, 2009 18:25
Show Gist options
  • Save jdeveloper/146356 to your computer and use it in GitHub Desktop.
Save jdeveloper/146356 to your computer and use it in GitHub Desktop.
#function that takes an array and a block and aplies the block to each element in a thread returning the results in a array
#it is in fact a parallel map
def parmap(arr,&block)
threads = arr.map do |element|
Thread.new do
block.call(element)
end
end
threads.each { |th| th.join }
threads.map { |th| th.value}
end
#example
#fetch pages in parallel
require 'net/http'
pages = %w( www.rubycentral.com
www.awl.com
www.pragmaticprogrammer.com
)
results = parmap pages do |page|
h = Net::HTTP.new(page, 80)
resp, data = h.get('/', nil )
data
end
results.each {|res| puts res}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment