Python 官方文档:入门教程 => 点击学习
这篇文章主要讲解了“python获取线程返回值的方式有哪些”,文中的讲解内容简单清晰,易于学习与理解,下面请大家跟着小编的思路慢慢深入,一起来研究和学习“Python获取线程返回值的方式有哪些”吧!方法一:使用全局变量的列表,来保存返回值r
这篇文章主要讲解了“python获取线程返回值的方式有哪些”,文中的讲解内容简单清晰,易于学习与理解,下面请大家跟着小编的思路慢慢深入,一起来研究和学习“Python获取线程返回值的方式有哪些”吧!
ret_values = []def thread_func(*args):...value = ...ret_values.append(value)
选择列表的一个原因是:列表的 append() 方法是线程安全的,CPython 中,GIL 防止对它们的并发访问。如果你使用自定义的数据结构,在并发修改数据的地方需要加线程锁。
如果事先知道有多少个线程,可以定义一个固定长度的列表,然后根据索引来存放返回值,比如:
from threading import Threadthreads = [None] * 10results = [None] * 10def 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() 方法只是等待线程函数结束,没有返回值,我们可以在此处返回函数的运行结果,代码如下:
from threading import Threaddef foo(arg):return arGClass 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._returntwrv = ThreadWithReturnValue(target=foo, args=("hello world",))twrv.start()print(twrv.join()) # 此处会打印 hello world。
这样当我们调用 thread.join() 等待线程结束的时候,也就得到了线程的返回值。
我觉得前两种方式实在太低级了,Python 的标准库 concurrent.futures 提供更高级的线程操作,可以直接获取线程的返回值,相当优雅,代码如下:
import concurrent.futuresdef foo(bar):return barwith 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! 8hello world! 3hello world! 5hello world! 2hello world! 9hello world! 7hello world! 4hello world! 0hello world! 1hello world! 6
感谢各位的阅读,以上就是“Python获取线程返回值的方式有哪些”的内容了,经过本文的学习后,相信大家对Python获取线程返回值的方式有哪些这一问题有了更深刻的体会,具体使用情况还需要大家实践验证。这里是编程网,小编将为大家推送更多相关知识点的文章,欢迎关注!
--结束END--
本文标题: Python获取线程返回值的方式有哪些
本文链接: https://www.lsjlt.com/news/357455.html(转载时请注明来源链接)
有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341
下载Word文档到电脑,方便收藏和打印~
2024-03-01
2024-03-01
2024-03-01
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
回答
回答
回答
回答
回答
回答
回答
回答
回答
回答
0