我这里的密码..。
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如何保持runner和loop thread运行?以及如何像这样修改代码?
我试过像Thread.abort_on_exception一样,但它会扼杀这个过程.
发布于 2015-10-19 10:11:12
捕获线程中的异常,并在主线程可访问的变量中设置错误(用于测试,可以使用一个全局变量,如:$thread_error)。
如果存在错误变量,则从主线程引发它。
您还可以使用队列在线程之间进行通信,但这样就无法利用多个线程。
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)
endhttps://stackoverflow.com/questions/33211229
复制相似问题