Python如何获取线程返回值,有多少种方式
Admin 2022-07-25 群英技术资讯 1028 次浏览
这篇文章给大家介绍了“Python如何获取线程返回值,有多少种方式”的相关知识,讲解详细,步骤过程清晰,有一定的借鉴学习价值,因此分享给大家做个参考,感兴趣的朋友接下来一起跟随小编看看吧。使用全局变量的列表,来保存返回值
ret_values = [] def thread_func(*args): ... value = ... ret_values.append(value)
选择列表的一个原因是:列表的 append() 方法是线程安全的,CPython 中,GIL 防止对它们的并发访问。如果你使用自定义的数据结构,在并发修改数据的地方需要加线程锁。
如果事先知道有多少个线程,可以定义一个固定长度的列表,然后根据索引来存放返回值,比如:
from threading import Thread
threads = [None] * 10
results = [None] * 10
def foo(bar, result, index):
result[index] = f"foo-{index}"
for i in range(len(threads)):
threads[i] = Thread(target=foo, args=('world!', results, i))
threads[i].start()
for i in range(len(threads)):
threads[i].join()
print (" ".join(results))
重写 Thread 的 join 方法,返回线程函数的返回值
默认的 thread.join() 方法只是等待线程函数结束,没有返回值,我们可以在此处返回函数的运行结果,代码如下:
from threading import Thread
def foo(arg):
return arg
class ThreadWithReturnValue(Thread):
def run(self):
if self._target is not None:
self._return = self._target(*self._args, **self._kwargs)
def join(self):
super().join()
return self._return
twrv = ThreadWithReturnValue(target=foo, args=("hello world",))
twrv.start()
print(twrv.join()) # 此处会打印 hello world。
这样当我们调用 thread.join() 等待线程结束的时候,也就得到了线程的返回值。
使用标准库 concurrent.futures
我觉得前两种方式实在太低级了,Python 的标准库 concurrent.futures 提供更高级的线程操作,可以直接获取线程的返回值,相当优雅,代码如下:
import concurrent.futures
def foo(bar):
return bar
with concurrent.futures.ThreadPoolExecutor(max_workers=10) as executor:
to_do = []
for i in range(10): # 模拟多个任务
future = executor.submit(foo, f"hello world! {i}")
to_do.append(future)
for future in concurrent.futures.as_completed(to_do): # 并发执行
print(future.result())
某次运行的结果如下:
hello world! 8
hello world! 3
hello world! 5
hello world! 2
hello world! 9
hello world! 7
hello world! 4
hello world! 0
hello world! 1
hello world! 6
本文分享了获取线程返回值的 3 种方法,推荐使用第三种
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:mmqy2019@163.com进行举报,并提供相关证据,查实之后,将立刻删除涉嫌侵权内容。
猜你喜欢
range()方法是Python中常用的方法, 但是在Python2和Python3中使用方法不同,下面看下它们的不同使用方法。range方法详解range(start, st
这篇文章主要介绍了pytorch_detach 切断网络反传方式,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
这篇文章主要介绍了Python探针完成调用库的数据提取,Python中可以通过sys.meta_path来实现import hook的功能,下文详细资料介绍,需要的小伙伴可以参考一下
这篇文章主要介绍了python编程开发之类型转换convert用法,结合实例形式分析了Python中常见的数据类型及类型转换convert的具体使用方法,需要的朋友可以参考下
Kivy 是用 Python 和 Cython 编写的,基于 OpenGL ES 2,支持各种输入设备并拥有丰富的部件库。本文将教你如何使用 Kivy 编写一款乒乓球游戏,感兴趣的可以动手试一试
成为群英会员,开启智能安全云计算之旅
立即注册关注或联系群英网络
7x24小时售前:400-678-4567
7x24小时售后:0668-2555666
24小时QQ客服
群英微信公众号
CNNIC域名投诉举报处理平台
服务电话:010-58813000
服务邮箱:service@cnnic.cn
投诉与建议:0668-2555555
Copyright © QY Network Company Ltd. All Rights Reserved. 2003-2020 群英 版权所有
增值电信经营许可证 : B1.B2-20140078 ICP核准(ICP备案)粤ICP备09006778号 域名注册商资质 粤 D3.1-20240008