Python获取线程返回值方法

之前有个需求需要用到Python多线程,但同时又需要获得线程执行函数后的情况,然而Python多线程并没有提供返回线程值的方法,因此需要通过其他的渠道来解决这个问题,查阅了相关资料,获取线程返回值的方法大致有如下三种,分别如下

方法一:使用全局变量的列表,保存返回值

ret_values = []
 
def thread_func(*args):
    ...
    value = ...
    ret_values.append(value)

Python列表的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() 方法只是等待线程函数结束,没有返回值,我们可以在此处返回函数的运行结果,当调用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
 
 
T = ThreadWithReturnValue(target=foo, args=("hello world",))
T.start()
print(T.join()) # 此处会打印 hello world。

方法三:使用标准库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

end!

  • 1
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

Swlaaa

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

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

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

打赏作者

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

抵扣说明:

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

余额充值