gpt4 book ai didi

ruby - 从线程循环中脱离出来

转载 作者:数据小太阳 更新时间:2023-10-29 08:04:04 25 4
gpt4 key购买 nike

我正在从(降序)按时间排序的画廊下载图像。我想停下来,当我们看到已经放下的照片时。

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com