lib/timeout.rb


DEFINITIONS

This source file includes following functions.


   1  #
   2  # timeout.rb -- execution timeout
   3  #
   4  # Copyright (C) 2000  Network Applied Communication Laboratory, Inc.
   5  # Copyright (C) 2000  Information-technology Promotion Agency, Japan
   6  #
   7  #= SYNOPSIS
   8  #
   9  #   require 'timeout'
  10  #   status = timeout(5) {
  11  #     # something may take time
  12  #   }
  13  #
  14  #= DESCRIPTION
  15  #
  16  # timeout executes the block.  If the block execution terminates successfully
  17  # before timeout, it returns true.  If not, it terminates the execution and
  18  # raise TimeoutError exception.
  19  #
  20  #== Parameters
  21  #
  22  #  : timout
  23  #
  24  #    The time in seconds to wait for block teminatation.   
  25  #
  26  #=end
  27  
  28  class TimeoutError<Interrupt
  29  end
  30  
  31  def timeout(sec, exception=TimeoutError)
  32    return yield if sec == nil
  33    begin
  34      x = Thread.current
  35      y = Thread.start {
  36        sleep sec
  37        x.raise exception, "execution expired" if x.alive?
  38      }
  39      yield sec
  40  #    return true
  41    ensure
  42      y.kill if y and y.alive?
  43    end
  44  end
  45  
  46  if __FILE__ == $0
  47    p timeout(5) {
  48      45
  49    }
  50    p timeout(5) {
  51      loop {
  52        p 10
  53        sleep 1
  54      }
  55    }
  56  end