how to get the return value from a thread in python?
阿新 • • 發佈:2019-02-09
Jake's answer is good, but if you don't want to use a threadpool (you don't know how many threads you'll need, but create them as needed) then a good way to transmit information between threads is the built-inQueue.Queue class, as it offers thread safety.
I created the following decorator to make it act in a similar fashion to the threadpool:
def threaded(f, daemon=False):importQueuedef 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.Queue()
t = threading.Thread(target=wrapped_f, args=(q,)+args, kwargs=kwargs)
t.daemon = daemon
t.start()
t.result_queue = q
return t
return wrap
Then you just use it as:
@threadeddef long_task(x):import time
x = x +5
time .sleep(5)return x
# 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
The decorated function creates a new thread each time it's called and returns a Thread object that contains the queue that will receive the result.