Last active
May 2, 2020 12:10
-
-
Save takuma-saito/e8e1a07e39735a78e33eb1705d70eb7d to your computer and use it in GitHub Desktop.
timeout.rb
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class TimeoutError < StandardError; end | |
def timeout(sec) | |
x = Thread.current | |
t = Thread.new do | |
begin | |
sleep sec | |
x.raise TimeoutError.new "Exceed maximum timeout value #{sec}s" | |
rescue e | |
x.raise e | |
end | |
end | |
return yield(sec) | |
ensure | |
if t | |
t.kill | |
t.join | |
end | |
end | |
t1 = Thread.new do | |
timeout(3) { | |
p 'a' | |
sleep 5 | |
p 'b' | |
} | |
end | |
t2 = Thread.new do | |
timeout(6) { | |
p 'c' | |
sleep 4 | |
raise StandardError.new 'error' | |
p 'd' | |
} | |
end | |
[t1, t2].each {|t| | |
begin | |
t.join.value | |
rescue TimeoutError => e | |
p e | |
end | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment