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

标签 ruby multithreading threadpool

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

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/

相关文章:

Java多线程使用 sleep 和中断

c# - Task.WaitAll 方法 (Task[], Int32) 过期时不释放线程

java - ThreadPool 不运行提交的任务

c - 使用 CreateThreadpoolWork/SubmitThreadpoolWork 时将不同的值传递给回调函数

ruby - Sinatra + Ruby : Random Number keeps changing every time I guess. 作用域问题?

ruby - AWS Elastic Beanstalk - 如何将现有环境从 Ruby 2.1 升级到 Ruby 2.2

ruby - 如何解决 "You need to have Ruby and Sass installed and in your PATH for this task to work"警告?

ruby - 用于使用 ruby​​ 大量插入 redis 的 ram 文件?

java - 在 Java 8 中将字符串转换为 java.util.Date

java - 线程输出到 GUI 文本字段