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