• Python 获取线程返回值方法


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

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

    1. ret_values = []
    2. def thread_func(*args):
    3. ...
    4. value = ...
    5. ret_values.append(value)

    Python列表的append()方法是线程安全的,在CPython中,GIL防止对列表并发访问,如果使用自定义的数据结构,在并发修改数据的地方需要添加线程锁。

    如果确定线程的数量,可以定义一个固定长度的列表,然后根据索引来存放返回值,比如:

    1. from threading import Thread
    2. threads = [None] * 10
    3. results = [None] * 10
    4. def foo(bar, result, index):
    5. result[index] = f"foo-{index}"
    6. for i in range(len(threads)):
    7. threads[i] = Thread(target=foo, args=('world!', results, i))
    8. threads[i].start()
    9. for i in range(len(threads)):
    10. threads[i].join()
    11. print (" ".join(results))

    方法二:重写Thread的join方法,返回线程函数的返回值

    默认的 thread.join() 方法只是等待线程函数结束,没有返回值,我们可以在此处返回函数的运行结果,当调用thread.join()等线程结束后,也就获得了线程的返回值,代码如下:

    1. from threading import Thread
    2. def foo(arg):
    3. return arg
    4. class ThreadWithReturnValue(Thread):
    5. def run(self):
    6. if self._target is not None:
    7. self._return = self._target(*self._args, **self._kwargs)
    8. def join(self):
    9. super().join()
    10. return self._return
    11. T = ThreadWithReturnValue(target=foo, args=("hello world",))
    12. T.start()
    13. print(T.join()) # 此处会打印 hello world。

    方法三:使用标准库concurrent.futures

    前两种方式较为普通(低级),Python 的标准库 concurrent.futures 提供更高级的线程操作,可以直接获取线程的返回值,相当优雅,代码如下:

    1. import concurrent.futures
    2. def foo(bar):
    3. return bar
    4. with concurrent.futures.ThreadPoolExecutor(max_workers=10) as executor:
    5. to_do = []
    6. for i in range(10): # 模拟多个任务
    7. future = executor.submit(foo, f"hello world! {i}")
    8. to_do.append(future)
    9. for future in concurrent.futures.as_completed(to_do): # 并发执行
    10. print(future.result())

    某次运行的结果如下:

    1. hello world! 8
    2. hello world! 3
    3. hello world! 5
    4. hello world! 2
    5. hello world! 9
    6. hello world! 7
    7. hello world! 4
    8. hello world! 0
    9. hello world! 1
    10. hello world! 6

    end!

  • 相关阅读:
    【C++ 科学计算】C++ 一维数据插值算法
    Java校园二手平台项目商城电商购物系统(含源码+论文+答辩PPT等)
    4个技巧告诉你,如何使用SMS促进业务销售?
    值得你收藏的Notes应用模板
    上线三天破百万点赞,涵盖90%以上的Java面试题,这份Java面试神技带你所向披靡
    竞赛 基于机器视觉的车道线检测
    我的创作纪念日
    【0114】libpq连接句柄PGconn介绍
    2022-07-30 mysql8执行慢SQL[Q17]分析
    Docker入门学习笔记
  • 原文地址:https://blog.csdn.net/Gefangen/article/details/126343344