Skip to content

Instantly share code, notes, and snippets.

@sethrh
Created May 28, 2014 17:53
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 sethrh/85ebaa437d75a0dc86ec to your computer and use it in GitHub Desktop.
Save sethrh/85ebaa437d75a0dc86ec to your computer and use it in GitHub Desktop.
Decorator / Context manager to wait and notify on conditions
from functools import wraps
from threading import Condition
"""
Usage:
cond = Condition()
Acquire the condition, wait for it, then do something:
@WaitOn(cond)
def f():
something()
or
def f():
with WaitOn();
something()
Acquire the condition, do something, then notify:
@NotifyOn(cond)
def g():
something()
or
def g():
with NotifyOn(cond):
something()
"""
class WaitOn:
def __init__(self, cond):
self.cond = cond
def __enter__(self):
self.cond.acquire()
self.cond.wait()
return self
def __exit__(self, type, value, traceback):
self.cond.release()
def __call__(self, fn):
@wraps(fn)
def deco(*args, **kwargs):
with self:
return fn(*args, **kwargs)
return deco
class NotifyOn:
def __init__(self, cond):
self.cond = cond
def __enter__(self):
self.cond.acquire()
return self
def __exit__(self, type, value, traceback):
self.cond.notify_all()
self.cond.release()
def __call__(self, fn):
@wraps(fn)
def deco(*args, **kwargs):
with self:
return fn(*args, **kwargs)
return deco
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment