处理Ruby线程中引发的异常

b5lpy0ml  于 11个月前  发布在  Ruby
关注(0)|答案(5)|浏览(135)

我正在寻找异常处理的经典问题的解决方案。考虑以下代码:

def foo(n)
  puts " for #{n}"
  sleep n
  raise "after #{n}"
end

begin
  threads = []
  [5, 15, 20, 3].each do |i|
    threads << Thread.new do
      foo(i)
    end
  end

  threads.each(&:join)      
rescue Exception => e
  puts "EXCEPTION: #{e.inspect}"
  puts "MESSAGE: #{e.message}"
end

字符串
此代码在5秒后捕获异常。
但是如果我将数组改为[15, 5, 20, 3],上面的代码会在15秒后捕获异常。简而言之,它总是捕获第一个线程引发的异常。
有什么想法吗,为什么会这样。为什么每次都不是在3秒后捕获异常?我如何捕获任何线程的第一个异常?

oiopk7p5

oiopk7p51#

如果你想让任何线程中的任何未处理的异常导致解释器退出,你需要将Thread::abort_on_exception=设置为true。未处理的异常会导致线程停止运行。如果你不将这个变量设置为true,异常只会在你为线程调用Thread#joinThread#value时引发。如果设置为true,它会在发生时引发,并传播到主线程。

Thread.abort_on_exception=true # add this

def foo(n)
    puts " for #{n}"
    sleep n
    raise "after #{n}"
end

begin
    threads = []
    [15, 5, 20, 3].each do |i|
        threads << Thread.new do
            foo(i)
        end
    end
    threads.each(&:join)

rescue Exception => e

    puts "EXCEPTION: #{e.inspect}"
    puts "MESSAGE: #{e.message}"
end

字符串
输出量:

for 5
 for 20
 for 3
 for 15
EXCEPTION: #<RuntimeError: after 3>
MESSAGE: after 3


注意:但是如果你想让任何特定的线程示例以这种方式引发异常,有类似的abort_on_exception= Thread示例方法:

t = Thread.new {
   # do something and raise exception
}
t.abort_on_exception = true

# Alternatively use Thread.current.abort_on_exception= 
# as first line within thread to ensure it is set before
# any other work is done by the thread.
t = Thread.new {
   Thread.current.abort_on_exception = true
   # do something and raise exception
}

vq8itlhq

vq8itlhq2#

Thread.class_eval do
  alias_method :initialize_without_exception_bubbling, :initialize
  def initialize(*args, &block)
    initialize_without_exception_bubbling(*args) {
      begin
        block.call
      rescue Exception => e
        Thread.main.raise e
      end
    }
  end
end

字符串

fumotvh3

fumotvh33#

延迟异常处理(灵感来自@Jason Ling)

class SafeThread < Thread

  def initialize(*args, &block)
    super(*args) do
      begin
        block.call
      rescue Exception => e
        @exception = e
      end
    end
  end

  def join
    raise_postponed_exception
    super
    raise_postponed_exception
  end

  def raise_postponed_exception
    Thread.current.raise @exception if @exception
  end

end

puts :start

begin
  thread = SafeThread.new do
    raise 'error from sub-thread'
  end

  puts 'do something heavy before joining other thread'
  sleep 1

  thread.join
rescue Exception => e
  puts "Caught: #{e}"
end

puts 'proper end'

字符串

huus2vyu

huus2vyu4#

这将等待第一个线程提升或返回(并重新提升):

require 'thwait'
def wait_for_first_block_to_complete(*blocks)
  threads = blocks.map do |block|
    Thread.new do
      block.call
    rescue StandardError
      $!
    end
  end
  waiter = ThreadsWait.new(*threads)
  value = waiter.next_wait.value
  threads.each(&:kill)
  raise value if value.is_a?(StandardError)
  value
end

字符串

gmol1639

gmol16395#

Jason Ling的回答会遗漏传递给Thread.new的任何参数。这会破坏Puma和其他宝石。为了避免这个问题,你可以用途:

Thread.class_eval do
  alias_method :initialize_without_exception_bubbling, :initialize
  def initialize(*args, &block)
    initialize_without_exception_bubbling(*args) {
      begin
        block.call(*args)
      rescue Exception => e
        Thread.main.raise e
      end
    }
  end
end

字符串

相关问题