Created
May 14, 2010 19:54
-
-
Save bpot/401579 to your computer and use it in GitHub Desktop.
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
# Implementation of Timeout with EventMachine timers | |
require 'timeout' | |
module EMTimeout | |
# TODO make sure EM is running and make sure this isn't called by the reactor thread | |
def timeout(sec, klass = nil) | |
return yield if sec == nil or sec.zero? | |
raise ThreadError, "timeout within critical session" if Thread.critical | |
exception = klass || Class.new(ExitException) | |
x = Thread.current | |
t = EM.add_timer(sec) { | |
x.raise exception, "execution expired" if x.alive? | |
} | |
yield sec | |
EM.delete_timer t | |
end | |
end | |
if __FILE__ == $0 | |
Thread.new { EM.run {} } | |
p timeout(5) { | |
45 | |
} | |
p timeout(5, TimeoutError) { | |
45 | |
} | |
p timeout(nil) { | |
54 | |
} | |
p timeout(0) { | |
54 | |
} | |
p timeout(5) { | |
loop { | |
p 10 | |
sleep 1 | |
} | |
} | |
end | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment