Created
May 19, 2020 18:54
-
-
Save meganlkm/72c073506b832bd40bbedf5004f52619 to your computer and use it in GitHub Desktop.
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
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