• 欢迎访问搞代码网站,推荐使用最新版火狐浏览器和Chrome浏览器访问本网站!
  • 如果您觉得本站非常有看点,那么赶紧使用Ctrl+D 收藏搞代码吧

python concurrent.futures模块的使用测试

python 搞代码 4年前 (2022-01-07) 25次浏览 已收录 0个评论
文章目录[隐藏]

大家都知道concurrent.futures 是 3.2 中引入的新模块,它为异步执行可调用对象提供了高层接口,今天通过本文给大家介绍python concurrent.futures模块的使用测试 ,感兴趣的朋友一起看看吧

概述

concurrent.futures 是 3.2 中引入的新模块,它为异步执行可调用对象提供了高层接口。
可以使用 ThreadPoolExecutor 来进行多线程编程,ProcessPoolExecutor 进行多进程编程,两者实现了同样的接口,这些接口由抽象类 Executor 定义。
这个模块提供了两大类型,一个是执行器类 Executor,另一个是 Future 类。
执行器用来管来源gaodai$ma#com搞$代*码*网理工作池,future 用来管理工作计算出来的结果,通常不用直接操作 future 对象,因为有丰富的 API。

说明

Python3.2开始,标准库为我们提供了concurrent.futures模块,它提供了ThreadPoolExecutor和ProcessPoolExecutor两个类,实现了对threading和multiprocessing的进一步抽象,对编写线程池/进程池提供了直接的支持.

 #! /usr/bin/env python # -*- coding: utf-8 -*-# # ------------------------------------------------------------------------------- # Name:         demo3 # Author:       yunhgu # Date:         2021/7/8 15:17 # Description: # ------------------------------------------------------------------------------- import os import time import threading from concurrent.futures import ProcessPoolExecutor, ThreadPoolExecutor, as_completed def work(x): time.sleep(1) temp = f"父进程{os.getppid()}:子进程{os.getpid()}:线程{threading.get_ident()}:{x}" return temp def sub_thread(): temp_list = [] with ThreadPoolExecutor(max_workers=3) as t: task_list = [t.submit(work, i) for i in range(5)] for task in as_completed(task_list): if task.done(): temp_list.append(task.result()) return temp_list def main(): print(f"主进程:{os.getpid()}") path_list = [] with ProcessPoolExecutor(max_workers=3) as p: task_list = [p.submit(sub_thread) for i in range(5)] for task in as_completed(task_list): if task.done(): path_list.append(task.result()) for path in path_list: print(path) if __name__ == '__main__': main()

不论你在什么时候开始,重要的是开始之后就不要停止。不论你在什么时候结束,重要的是结束之后就不要悔恨。

到此这篇关于python concurrent.futures模块的使用测试 的文章就介绍到这了,更多相关python concurrent使用内容请搜索gaodaima搞代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持gaodaima搞代码网

以上就是python concurrent.futures模块的使用测试的详细内容,更多请关注gaodaima搞代码网其它相关文章!


搞代码网(gaodaima.com)提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发送到邮箱[email protected],我们会在看到邮件的第一时间内为您处理,或直接联系QQ:872152909。本网站采用BY-NC-SA协议进行授权
转载请注明原文链接:python concurrent.futures模块的使用测试
喜欢 (0)
[搞代码]
分享 (0)
发表我的评论
取消评论

表情 贴图 加粗 删除线 居中 斜体 签到

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址