如何从python中的线程获取返回值?

编程入门 行业动态 更新时间:2024-10-26 03:22:32
本文介绍了如何从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中的线程获取返回值?

本文发布于:2023-10-11 22:25:58,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1483014.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:线程   返回值   python

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!