Created
July 13, 2009 18:25
-
-
Save jdeveloper/146356 to your computer and use it in GitHub Desktop.
This file contains 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
#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