下面的函数 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
。
原文由 wim 发布,翻译遵循 CC BY-SA 4.0 许可协议
在 Python 3.2+ 中,stdlib
concurrent.futures
模块为threading
提供了更高级别的 API,包括将工作线程的返回值或异常传递回主线程: