[英]Ruby: how to handler thread exception?
my code here... 我的代码在这里...
require 'thread'
$temp = Thread.new do
loop do
puts 'loop me'
begin
puts "try thread"
raise Exception.new('QwQ') if rand > 0.5
puts "skip try"
rescue
puts "QwQ"
end
sleep(0.5)
end
puts '...WTF'
end
loop do
puts "runner #{Thread.list.length} #{$temp.status}"
sleep(2)
end
how to keep runner
and loop thread
running? 如何保持
runner
和loop thread
运行? and how to fix it like this code? 以及如何像这样的代码来解决?
I tried like Thread.abort_on_exception
, but it will kill the process... 我尝试像
Thread.abort_on_exception
一样,但是会杀死进程。
Catch the exception inside the thread, and set the error in a variable accessible by the main thread (for testing you could use a global variable like so: $thread_error). 在线程内捕获异常,然后在主线程可访问的变量中设置错误(为进行测试,您可以使用全局变量,例如:$ thread_error)。
If the error-variable exists, then raise it from the main thread. 如果错误变量存在,则从主线程引发它。
You could also use a queue to communicate between the threads, but then it wouldn't be able to utilize multiple threads. 您还可以使用队列在线程之间进行通信,但是这样就无法利用多个线程。
require 'thread'
$temp = Thread.new do
begin
loop do
puts 'loop me'
begin
puts "try thread"
raise Exception.new('QwQ') if rand > 0.5
puts "skip try"
rescue
puts "QwQ"
end
sleep(0.5)
end
puts '...WTF'
rescue Exception => e
$thread_error = e
raise e
end
end
loop do
puts "runner #{Thread.list.length} #{$temp.status}"
raise $thread_error if $thread_error
sleep(2)
end
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.