Created
August 18, 2011 17:01
-
-
Save denik/1154529 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
while not process_shutdown: # only process if process_shutdown has not be signalled yet | |
with process_shutdown: | |
# means Interrupt will be raised here asynchronously | |
x = do_something() | |
# in some other greenlet: | |
process_shutdown.signal() |
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
from contextlib import contextmanager | |
from gevent import getcurrent, GreenletExit | |
from gevent.pool import Group | |
class Interrupt(GreenletExit): | |
def __init__(self, message=None): | |
BaseException.__init__(self, message) | |
self.greenlets = Group() | |
self.signalled = False | |
def __nonzero__(self): | |
return self.signalled | |
@contextmanager | |
def catch(self): | |
try: | |
yield | |
except Interrupt, ex: | |
if ex is not self: | |
raise | |
def enter(self): | |
if self.signalled: | |
raise self | |
self.greenlets.add(getcurrent()) | |
def exit(self): | |
self.greenlets.discard(getcurrent()) | |
def __enter__(self): | |
self.enter() | |
return self | |
def __exit__(self, typ, value, tb): | |
self.exit() | |
def signal(self, timeout=0): | |
self.signalled = True | |
if timeout <= 0: | |
self.greenlets.kill(exception=self, block=False) | |
else: | |
self.greenlets.kill(exception=self, block=True, timeout=timeout) | |
process_shutdown = Interrupt('Process shutdown') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
123