Skip to content

Instantly share code, notes, and snippets.

@takuma-saito
Last active May 2, 2020 12:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save takuma-saito/e8e1a07e39735a78e33eb1705d70eb7d to your computer and use it in GitHub Desktop.
Save takuma-saito/e8e1a07e39735a78e33eb1705d70eb7d to your computer and use it in GitHub Desktop.
timeout.rb
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