python concurrent.futures模块的使用测试

作者:不能说的秘密 时间:2023-01-30 16:48:59 

概述

concurrent.futures 是 3.2 中引入的新模块,它为异步执行可调用对象提供了高层接口。
可以使用 ThreadPoolExecutor 来进行多线程编程,ProcessPoolExecutor 进行多进程编程,两者实现了同样的接口,这些接口由抽象类 Executor 定义。
这个模块提供了两大类型,一个是执行器类 Executor,另一个是 Future 类。
执行器用来管理工作池,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模块的使用测试

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

来源:https://www.cnblogs.com/yunhgu/p/15005535.html

标签:python,concurrent
0
投稿

猜你喜欢

  • python对csv文件追加写入列的方法

    2022-11-14 01:56:29
  • oracle 多个字符替换实现

    2009-10-23 17:50:00
  • python闭包、深浅拷贝、垃圾回收、with语句知识点汇总

    2023-09-11 13:20:31
  • ASP状态封装类Cache、Cookie & Session

    2008-05-11 19:33:00
  • python机器学习之神经网络

    2023-11-10 21:39:19
  • ASP GetRef 函数指针试探

    2011-03-16 11:09:00
  • Python中使用matplotlib模块errorbar函数绘制误差棒图实例代码

    2022-11-09 17:01:42
  • Oracle中时间日期转化函数to_date和to_char的具体使用

    2023-07-15 20:20:20
  • asp使用jmail4.3的模块

    2010-03-17 20:58:00
  • ASP 常见的连接字符串写法(access2007)

    2011-03-25 10:40:00
  • Python打印scrapy蜘蛛抓取树结构的方法

    2022-01-16 03:46:18
  • 几个常用的js小函数

    2007-09-19 12:59:00
  • 用YSlow评分插件分析我们页面

    2008-08-26 11:48:00
  • 浏览器根据什么来判定脚本失控?[译]

    2009-02-20 13:36:00
  • PyTorch实现MNIST数据集手写数字识别详情

    2021-08-03 17:30:36
  • asp如何刪除客户端的Cookies?

    2010-05-18 18:25:00
  • 如何使用数据绑定控件实现不换页提交数据?

    2010-05-16 15:17:00
  • php结合js实现点击超链接执行删除确认操作

    2023-11-15 03:30:51
  • python 密码验证(滑块验证)

    2021-01-24 02:32:18
  • 解读ASP.NET 5 & MVC6系列教程(2):初识项目

    2023-06-28 02:10:47
  • asp之家 网络编程 m.aspxhome.com