Created
May 28, 2014 17:53
-
-
Save sethrh/85ebaa437d75a0dc86ec to your computer and use it in GitHub Desktop.
Decorator / Context manager to wait and notify on conditions
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 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