Skip to content

Instantly share code, notes, and snippets.

@calvinfroedge
Last active October 2, 2015 19:08
Show Gist options
  • Save calvinfroedge/606ed7c152656ffd7e91 to your computer and use it in GitHub Desktop.
Save calvinfroedge/606ed7c152656ffd7e91 to your computer and use it in GitHub Desktop.
Threads + Futures in Python
'''
Pros:
- Get the spawned thread (use thread.join() to wait on it, for example)
- Get the future
- Calling worker.future.result() will automatically raise an exception in the main thread
'''
from concurrent.futures import Future
import threading
import time
def test():
time.sleep(2)
return 'test'
raise Exception('foo')
class Worker(object):
def __init__(self, fn, args=()):
self.future = Future()
self._fn = fn
self._args = args
def start(self, cb=None):
self._cb = cb
self.future.set_running_or_notify_cancel()
thread = threading.Thread(target=self.run, args=())
thread.daemon = True #this will continue thread execution after the main thread runs out of code - you can still ctrl + c or kill the process
thread.start()
return thread
def run(self):
try:
self.future.set_result(self._fn(*self._args))
except BaseException as e:
self.future.set_exception(e)
if(self._cb):
self._cb(self.future.result())
worker = Worker(test)
thread = worker.start(lambda x: print('callback', x))
while True:
print("waiting")
if worker.future.done():
exc = worker.future.exception()
print('exception?', exc)
result = worker.future.result()
print('result', result)
break
time.sleep(0.25)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment