【Python】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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

别出BUG求求了

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值