本文介绍了如何从python中的线程获取返回值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下面的函数foo返回字符串'foo'.如何获取从线程目标返回的值'foo'?

The function foo below returns a string 'foo'. How can I get the value 'foo' which is returned from the thread's target?

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.

The "one obvious way to do it", shown above, doesn't work: thread.join() returned None.

推荐答案

在Python 3.2+中,stdlib concurrent.futures 模块为threading提供了更高级别的API,包括将返回值或异常从工作线程传递回主线程:

In Python 3.2+, stdlib concurrent.futures module provides a higher level API to threading, including passing return values or exceptions from a worker thread back to the main thread:

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)

这篇关于如何从python中的线程获取返回值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-05 11:44