2013-01-04 97 views
3

我是相當新的紅寶石輯陣線程和感到困惑於如何開始。我目前正在構建一個應用程序,它需要獲取大量圖像,所以我想在不同的線程中完成它。我希望程序按照下面的代碼執行。圖片添加到隊列中取出,然後抓住他們

問題:我在這裏看到的問題是,bar_method將得到完成獲取更快的線程將結束這樣的事情會越來越添加到隊列中,但不會被處理。是否有任何可能的同步方式,它會提醒bar_method線程有新項目已添加到隊列中,並且如果bar_method更早完成,它應該進入睡眠狀態並等待將新項目添加到隊列中?

def foo_method 
    queue created - consists of url to fetch and a callback method 
    synch = Mutex.new 
    Thread.new do 
    bar_method synch, queue 
    end 
    100000.times do 
    synch.synchronize do 
     queue << {url => img_url, method_callback => the_callback} 
    end 
    end 
end 
def bar_method synch_obj, queue 
    synch_obj.synchronize do 
    while queue isn't empty 
     pop the queue. fetch image and call the callback 
    end 
    end 
end 

回答

2

如果需要從互聯網上檢索文件,並使用並行請求,我會強烈建議Typhoeus and Hydra

從文檔:

hydra = Typhoeus::Hydra.new 
10.times.map{ hydra.queue(Typhoeus::Request.new("www.example.com", followlocation: true)) } 
hydra.run 

您可以設置併發連接的水潤數量:

:max_concurrency(整數) - 最大併發連接創建的數量。默認值爲200.

作爲第二項建議請查看Curb。再次,從它的文檔:

# make multiple GET requests 
easy_options = {:follow_location => true} 
multi_options = {:pipeline => true} 

Curl::Multi.get('url1','url2','url3','url4','url5', easy_options, multi_options) do|easy| 
    # do something interesting with the easy response 
    puts easy.last_effective_url 
end 

兩者都建立在Curl的頂部,所以他們的底層技術或其穩健性沒有真正的區別。不同之處在於您可以使用的命令。

另一個的寶石,得到了很多關注的是EventMachine的。它有EM-HTTP-Request允許的併發請求:

EventMachine.run { 
    http1 = EventMachine::HttpRequest.new('http://google.com/').get 
    http2 = EventMachine::HttpRequest.new('http://yahoo.com/').get 

    http1.callback { } 
    http2.callback { } 
end 
相關問題