Skip to content

Instantly share code, notes, and snippets.

@ydm
Created January 21, 2014 09:12
Show Gist options
  • Select an option

  • Save ydm/8536798 to your computer and use it in GitHub Desktop.

Select an option

Save ydm/8536798 to your computer and use it in GitHub Desktop.
Future task implementation in Python
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