10

open-uriを使用して複数の同時接続を開くにはどうすればよいですか?どういうわけか糸脱毛や繊維を使う必要があると思いますが、よくわかりません。

コード例:

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
4

5 に答える 5

11

Peachに似ているが、積極的に更新されているParallelと呼ばれる宝石もあります。

于 2011-09-26T21:57:59.573 に答える
8

私はこれがあなたにアイデアを与えることを願っています:

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
于 2011-09-26T22:02:04.703 に答える
4
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
于 2014-07-13T07:18:20.867 に答える
2

スレッドを使用する簡単な方法:

threads = []

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

threads.each(&:join)
于 2017-06-30T20:24:30.047 に答える
-1

peachこれを可能にする(https://rubygems.org/gems/peach )と呼ばれる宝石があります:

require "peach"

array_of_urls_to_process.peach do |url|
  do_something(get_doc(url))
end
于 2011-09-26T21:43:34.650 に答える