【发布时间】:2021-05-27 18:55:28
【问题描述】:
过去一周我一直在尝试 Ruby 中的多线程概念。
为了练习,我正在设计一个文件下载器,它对一组 URL 发出并行请求。目前我需要在触发中断信号时安全地关闭线程。我已经阅读了多线程和在运行时捕获信号的理论。然而,尽管有了这些理论知识,我仍然不知道如何在实践中使用它们。
无论如何,我将把我的概念验证工作留在下面。
class MultiThread
attr_reader :limit, :threads, :queue
def initialize(limit)
@limit = limit
@threads = []
@queue = Queue.new
end
def add(*args, &block)
queue << [block, args]
end
def invoke
1.upto(limit).each { threads << spawn_thread }
threads.each(&:join)
end
private
def spawn_thread
Thread.new do
Thread.handle_interrupt(RuntimeError => :on_blocking) do
# Nothing to do
end
until queue.empty?
block, args = queue.pop
block&.call(*args)
end
end
end
end
urls = %w[https://example.com]
thread = MultiThread.new(2)
urls.each do |url|
thread.add do
puts "Downloading #{url}..."
sleep 1
end
end
thread.invoke
【问题讨论】:
-
你有什么问题?有错误吗?你得到意外的输出吗?
-
让我澄清一下。老实说,我不知道我应该在
handle_interrupt块下放什么。但是,当我添加Process.kill('INT', Process.pid)时出现以下错误。它会导致不受控制的终止。sh Downloading... t.rb:18:in `join': Interrupt
标签: ruby multithreading graceful-shutdown