Skip to content

Instantly share code, notes, and snippets.

@denik
Created August 18, 2011 17:01
Show Gist options
  • Save denik/1154529 to your computer and use it in GitHub Desktop.
Save denik/1154529 to your computer and use it in GitHub Desktop.
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()
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')
@denik
Copy link
Author

denik commented Aug 18, 2011

123

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment