下面的函数foo返回一个字符串'foo'。如何获取'foo'从线程目标返回的值?
foo
'foo'
from threading import Thread def foo(bar): print('hello {}'.format(bar)) return 'foo' thread = Thread(target=foo, args=('world!',)) thread.start() return_value = thread.join()
上面显示的“一种明显的方法”不起作用:thread.join()返回None.
thread.join()
None
在 Python 3.2+ 中,stdlibconcurrent.futures模块为 提供了更高级别的 API threading,包括将工作线程的返回值或异常传递回主线程:
concurrent.futures
threading
import concurrent.futures def foo(bar): print('hello {}'.format(bar)) return 'foo' with concurrent.futures.ThreadPoolExecutor() as executor: future = executor.submit(foo, 'world!') return_value = future.result() print(return_value)