【问题标题】:Ruby: how to handler thread exception?Ruby:如何处理线程异常?
【发布时间】:2016-01-17 14:41:16
【问题描述】:

我的代码在这里...

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

如何保持runnerloop thread 运行?以及如何像这段代码一样修复它?

我试过 Thread.abort_on_exception ,但它会杀死进程...

【问题讨论】:

  • hmm......我尝试将所有rescue 修复为rescue Exception => e 会好的,但是为什么!?!?
  • 好吧...我明白了,ruby rescue 默认是StandardErrorStandardError 超类是Exception ...

标签: ruby multithreading exception


【解决方案1】:

在线程内捕获异常,并将错误设置在主线程可访问的变量中(为了测试,您可以使用像这样的全局变量:$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)
end

【讨论】:

    猜你喜欢
    • 2012-02-24
    • 1970-01-01
    • 2013-09-10
    • 1970-01-01
    • 2013-10-06
    • 2014-03-23
    • 2012-08-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多