Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
import time
from queue import Queue
from threading import Thread
def threaded(f, daemon=False):
def wrapped_f(q, *args, **kwargs):
"""this function calls the decorated function and puts the
result in a queue"""
ret = f(*args, **kwargs)
q.put(ret)
def wrap(*args, **kwargs):
"""this is the function returned from the decorator. It fires off
wrapped_f in a new thread and returns the thread object with
the result queue attached"""
q = Queue()
t = Thread(target=wrapped_f, args=(q,) + args, kwargs=kwargs)
t.daemon = daemon
t.start()
t.result_queue = q
return t
return wrap
@threaded
def long_task(x, sleeptime=5):
# x = x + 5
time.sleep(sleeptime)
return x
q = Queue()
for i in range(10):
y = long_task(i)
q.put(y)
for i in range(10, 20):
y = long_task(i, 2)
q.put(y)
while not q.empty():
y = q.get()
print(f"{y.result_queue.get()} {y}")
# does not block, returns Thread object
# y = long_task(10)
# print(y)
# this blocks, waiting for the result
# result = y.result_queue.get()
# print(result)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.