广告
返回顶部
首页 > 资讯 > 后端开发 > Python >详解Python获取线程返回值的三种方式
  • 523
分享到

详解Python获取线程返回值的三种方式

2024-04-02 19:04:59 523人浏览 薄情痞子

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 种方法,推荐使用第三种

到此这篇关于详解Python获取线程返回值的三种方式的文章就介绍到这了,更多相关Python获取线程返回值内容请搜索编程网以前的文章或继续浏览下面的相关文章希望大家以后多多支持编程网!

--结束END--

本文标题: 详解Python获取线程返回值的三种方式

本文链接: https://www.lsjlt.com/news/119182.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

本篇文章演示代码以及资料文档资料下载

下载Word文档到电脑,方便收藏和打印~

下载Word文档
猜你喜欢
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作