Python 获取线程返回值的三种方式
2023-02-25 18:01:40 时间
提到线程,你的大脑应该有这样的印象:我们可以控制它何时开始,却无法控制它何时结束,那么如何获取线程的返回值呢?今天就分享一下自己的一些做法。
方法一:使用全局变量的列表,来保存返回值
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
相关文章
- 基于Python的人脸识别考勤监控
- Python答题游戏
- Python调用百度API实现图像识别
- Python全栈疫情分析项目
- Python-基础-if语句快速入门
- Python-基础-循环语句快速入门
- Python-GUI签名
- 【2】VScode 搭建python和tensorflow环境
- python 简易时钟
- 【1】windows系统如何安装后缀是whl的python库
- 【2】超级详细Python-matplotlib画图,手把手教你画图!(线条颜色、大小、线形、标签)
- 【4】python读写文件操作---详细讲解!
- 【2】Anaconda下:ipython文件的打开方式,Jupyter Notebook中运行.py文件,快速打开ipython文件的方法!
- 【编写环境一】遇到常见python函数处理方式
- 【编写环境二】python库scipy.stats各种分布函数生成、以及随机数生成【泊松分布、正态分布等】
- Python xlwt数据保存到 Excel中以及xlrd读取excel文件画图
- 强化学习技巧三:Python多进程
- 强化学习技巧五:numba提速python程序
- 【7】python_matplotlib 输出(保存)矢量图方法;画图时图例说明(legend)放到图像外侧;Python_matplotlib图例放在外侧保存时显示不完整问题解决
- 【8】python_matplotlib改变横坐标和纵坐标上的刻度(ticks)、sagemath-list_plot()调整图例(legend)中点的数量、Matplotlib画各种论文图