我正在从(降序)按时间排序的画廊下载图像。我想停下来,当我们看到已经放下的照片时。
require 'thread/pool'
def getimg(uri)
#...
if File.exist? filename
raise "Already done." # something like this
end
#...
end
pool = Thread.pool(4)
thumbs.each do |a|
pool.process {
getimg(URI(a.attr('href')))
}
end
最佳答案
如何传递一个池对象并使用 pool.shutdown
?
require 'thread/pool'
def getimg(uri, pool) # <----
#...
if File.exist? filename
pool.shutdown # <--------
return # <------
end
#...
end
pool = Thread.pool(4)
thumbs.each do |a|
pool.process {
getimg(URI(a.attr('href')), pool) # <----
}
end
根据 the Thread::Pool#process
code comment :
Shut down the pool, it will block until all tasks have finished running.
更新
使用 shutdown!
而不是 shutdown
。
shutown! Shut down the pool instantly without finishing to execute tasks.
关于ruby - 从线程循环中脱离出来,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25582837/