Created
January 21, 2014 09:12
-
-
Save ydm/8536798 to your computer and use it in GitHub Desktop.
Future task implementation in Python
This file contains hidden or 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
| class Future(object): | |
| def __init__(self, func, *args, **kwargs): | |
| self._lock = threading.Lock() | |
| self._thread = threading.Thread(target=self._locked(func), args=args, | |
| kwargs=kwargs) | |
| self._result = None | |
| self._done = False | |
| def _locked(self, func): | |
| @functools.wraps(func) | |
| def wrapper(*args, **kwargs): | |
| self._lock.acquire() | |
| try: | |
| self._result = func(*args, **kwargs) | |
| self._done = True | |
| finally: | |
| self._lock.release() | |
| return wrapper | |
| def __call__(self): | |
| # Block until the lock is acquired | |
| self._lock.acquire() | |
| try: | |
| return self._result | |
| finally: | |
| self._lock.release() | |
| def start(self): | |
| return self._thread.start() | |
| @property | |
| def done(self): | |
| return self._done |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment