ruby - 如何优雅地关闭 Ruby 中的线程
问题描述
过去一周我一直在尝试 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
令人困惑。试试这个,我基于connection_pool
eg 使用的 gem puma
。
$stdout.sync = true
threads = 3.times.map { |i|
Thread.new {
Thread.handle_interrupt(Exception => :never) do
begin
Thread.handle_interrupt(Exception => :immediate) do
puts "Thread #{i} doing work"
sleep 1000
end
ensure
puts "Thread #{i} cleaning up"
end
end
}
}
Signal.trap("INT") {
puts 'Exiting gracefully'
threads.each { |t|
puts 'killing thread'
t.kill
}
exit
}
threads.each { |t| t.join }
输出:
Thread 1 doing work
Thread 2 doing work
Thread 0 doing work
^CExiting gracefully
killing thread
killing thread
killing thread
Thread 0 cleaning up
Thread 1 cleaning up
Thread 2 cleaning up
推荐阅读
- python - 向 discord.py 音乐机器人添加队列命令
- c# - C# 从 XslCompiledTransform.Transform 的 XML 中删除不支持 UTF-8 的值
- android - React-Native 项目未在 Expo go 应用程序中打开
- aws-sdk-js - RedshiftDataClient BatchExecuteStatement 将所有查询合二为一
- python - 如何在 Python 中从此文本文件中获取接口名称和 IP 地址
- dataframe - 迭代元组列表以创建新列
- html - 嵌入的 Youtube 视频未填满屏幕
- java - 如何简化太多if条件并捕获java中的错误输出字段
- python - 我将如何使用 python split() 方法,但它以多个字符拆分的方式,而不仅仅是输入的特定字符串?
- java - testImplementation 的 Gradle 配置不起作用