2011-09-26 12 views
9

का उपयोग कर समानांतर में एक ऐरे में आइटम को कैसे संसाधित करें I'm looking है कि मैं ओपन-यूरी का उपयोग करके एकाधिक समवर्ती कनेक्शन खोलने के बारे में कैसे जा सकता हूं? मुझे लगता है कि मुझे कुछ थ्रेडिंग या फाइबर का उपयोग करने की ज़रूरत है, लेकिन मुझे यकीन नहीं है।रूबी (और ओपन-यूरी)

उदाहरण कोड:

def get_doc(url) 
    begin 
    Nokogiri::HTML(open(url).read) 
    rescue Exception => ex 
    puts "Failed at #{Time.now}" 
    puts "Error: #{ex}" 
    end 
end 

array_of_urls_to_process = [......] 

# How can I iterate over items in the array in parallel (instead of one at a time?) 
array_of_urls_to_process.each do |url| 
    x = get_doc(url) 
    do_something(x) 
end 

उत्तर

10

वहाँ भी एक रत्न Parallel कहा जाता है जो पीच के समान है, लेकिन है सक्रिय रूप से अद्यतन किया गया।

-1

एक रत्न peach (https://rubygems.org/gems/peach) कहा जाता है जो आप यह कर देता है नहीं है:

require "peach" 

array_of_urls_to_process.peach do |url| 
    do_something(get_doc(url)) 
end 
+0

मणि केवल jruby है –

7

मैं इस आप एक विचार देता है आशा:

def do_something(url, secs) 
    sleep secs #just to see a difference 
    puts "Done with: #{url}" 
end 

threads = [] 
urls_ary = ['url1', 'url2', 'url3'] 

urls_ary.each_with_index do |url, i| 
    threads << Thread.new{ do_something(url, i+1) } 
    puts "Out of loop #{i+1}" 
end 
threads.each{|t| t.join} 

शायद की तरह Array के लिए एक विधि बनाने:

class Array 
    def thread_each(&block) 
     inject([]){|threads,e| threads << Thread.new{yield(e)}}.each{|t| t.join} 
    end 
end 

[1, 2, 3].thread_each do |i| 
    sleep 4-i #so first one ends later 
    puts "Done with #{i}" 
end 
2
module MultithreadedEach 
    def multithreaded_each 
    each_with_object([]) do |item, threads| 
     threads << Thread.new { yield item } 
    end.each { |thread| thread.join } 
    self 
    end 
end 

उपयोग:

arr = [1,2,3] 

arr.extend(MultithreadedEach) 

arr.multithreaded_each do |n| 
    puts n # Each block runs in it's own thread 
end 
0

एक सरल विधि का उपयोग धागे:

threads = [] 

[1, 2, 3].each do |i| 
    threads << Thread.new { puts i } 
end 

threads.each(&:join) 
संबंधित मुद्दे