Handling exceptions raised in a Ruby thread

前端 未结 4 1620
陌清茗
陌清茗 2020-12-09 14:49

I am looking for a solution of classic problem of exception handling. Consider following piece of code:

def foo(n)
  puts \" for #{n}\"
  sleep n
  raise \"a         


        
4条回答
  •  渐次进展
    2020-12-09 15:27

    This will wait for the first thread to either raise or return (and re-raise):

    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
    

提交回复
热议问题