mirror of
https://github.com/ruby/ruby.git
synced 2022-11-09 12:17:21 -05:00
9d22a06ea0
rb_ary_values_at. follow DRY principle. * re.c (match_values_at): values_at should understand ranges. * struct.c (rb_struct_values_at): ditto. * struct.c (inspect_struct): inspect format changed; add "struct " at the top. * sprintf.c (rb_f_sprintf): "%p" specifier for inspect output. (RCR#68) * eval.c (rb_mod_undef_method): allow "undef_method" to accept multiple arguments. (RCR#146) * lib/timeout.rb: put timeout in Timeout module. (RCR#121) [ruby-talk:61028] * re.c (match_groups): new method added. (RCR#139) * variable.c (rb_mod_const_of): should exclude constant defined in Object, unless retrieving constants of Object. * string.c (rb_str_new4): do not allocate new string if original is frozen or already have copy-on-write entry. [ruby-talk:74940] git-svn-id: svn+ssh://ci.ruby-lang.org/ruby/trunk@4031 b2dd03c8-39d4-4d8f-98ff-823fe69b080e
69 lines
1.2 KiB
Ruby
69 lines
1.2 KiB
Ruby
#
|
|
# timeout.rb -- execution timeout
|
|
#
|
|
# Copyright (C) 2000 Network Applied Communication Laboratory, Inc.
|
|
# Copyright (C) 2000 Information-technology Promotion Agency, Japan
|
|
#
|
|
#= SYNOPSIS
|
|
#
|
|
# require 'timeout'
|
|
# status = timeout(5) {
|
|
# # something may take time
|
|
# }
|
|
#
|
|
#= DESCRIPTION
|
|
#
|
|
# timeout executes the block. If the block execution terminates successfully
|
|
# before timeout, it returns true. If not, it terminates the execution and
|
|
# raise TimeoutError exception.
|
|
#
|
|
#== Parameters
|
|
#
|
|
# : timout
|
|
#
|
|
# The time in seconds to wait for block teminatation.
|
|
#
|
|
# : [exception]
|
|
#
|
|
# The exception classs to be raised on timeout.
|
|
#
|
|
#=end
|
|
|
|
module Timeout
|
|
class Error<Interrupt
|
|
end
|
|
|
|
def timeout(sec, exception=Error)
|
|
return yield if sec == nil
|
|
begin
|
|
x = Thread.current
|
|
y = Thread.start {
|
|
sleep sec
|
|
x.raise exception, "execution expired" if x.alive?
|
|
}
|
|
yield sec
|
|
# return true
|
|
ensure
|
|
y.kill if y and y.alive?
|
|
end
|
|
end
|
|
module_function :timeout
|
|
end
|
|
|
|
# compatible
|
|
def timeout(n, &block)
|
|
Timeout::timeout(n, &block)
|
|
end
|
|
TimeoutError = Timeout::Error
|
|
|
|
if __FILE__ == $0
|
|
p timeout(5) {
|
|
45
|
|
}
|
|
p timeout(5) {
|
|
loop {
|
|
p 10
|
|
sleep 1
|
|
}
|
|
}
|
|
end
|