首页 > 其他分享 >concurrent.futures 模块

concurrent.futures 模块

时间:2023-03-31 16:46:01浏览次数:38  
标签:__ ... res futures concurrent 线程 模块 main pool

应用场景

# 什么时候用池
池的功能是限制启动的进程数或线程数
# 什么时候应该限制
当并发的任务数量远远超过了计算机的承受能力时,
即无法一次性开启过多的进程数或线程数时,
就应该用池的概念,将开启的进程数或线程数限制在计算机的可承受范围内

# 提交任务的两种形式
1. 同步:提交完任务后就在原地等待,直到任务运行完毕后拿到任务的返回值,再继续运行下一行代码
2. 异步:提交完任务后不在原地等待,直接运行下一行代码,任务的返回值

线程池

'''
线程池由concurrent.futures 下的ThreadPoolExecutor提供
submit(fn,*args,**kwarg s)将函数fn提交给线程池,
map(fn,*iterables,timeout=None,chunksize =1) 启动多线程,让函数fn分别使用后面的可迭代参数
	map的结果是生成器类型的数据,映射函数名字对应的结果保存在map object中
shutdown(wait = True) 关闭线程池,已经关闭的线程池不能再添加线程,可以用上下文管理器,自动关闭
'''

'''
使用submit() 函数提交后会返回future 对象
cancel() 可以取消该线程,如果线程正则运行,不可取消并返回Fasle,否则取消,并返回True
cancelled() 返回线程是否被取消
running() 返回线程是否正在运行
done() 返回线程是否完成,包括取消和正常完成
result()获取该线程的返回值,会阻塞线程,timeout 是阻塞时间,阻塞时间内获取不到就不要了,报错
add_done_callback(fn) 线程结束后执行fn回调函数

# -*- coding: utf-8 -*-
import os
import random
import time
from concurrent.futures import ProcessPoolExecutor, ThreadPoolExecutor


def task(n):
    print(f"{os.getpid()} is run..")
    time.sleep(n)
    # print('f')
    return n ** 2

# if __name__ == '__main__':
#     pool = ProcessPoolExecutor(max_workers=4)
#     start = time.perf_counter()
#     res_list = [pool.submit(task, random.randint(1, 5)).result() for i in range(5)]
#     pool.shutdown(wait=True)
#
#     # res = [res.result() for res in res_list]
#     end = time.perf_counter()
#     print(res_list)  # [1, 4, 4, 25, 9]
#     print(f'main... {end - start}')  # main... 13.29411249999248 1+2+2+5+3


if __name__ == '__main__':
    pool = ProcessPoolExecutor(max_workers=4)
    start = time.perf_counter()
    res_list = [pool.submit(task, random.randint(1, 5)) for i in range(5)]
    pool.shutdown(wait=True)

    res = [res.result() for res in res_list]
    end = time.perf_counter()
    print(res)  # [9, 25, 4, 25, 4]
    print(f'main... {end - start}')  # main... 5.186168200001703 5
	

# if __name__ == '__main__':
#     pool = ProcessPoolExecutor(max_workers=4)
#     start = time.perf_counter()
#     for i in range(10):
#         # pool.submit(task,args = random.randint(1,5))
#		  # main...0.021992599999066442,多进程执行结果
#         res =pool.submit(task,2)
#		  main...0.018832400004612282 604 is run..14160 is run..
#         # res = pool.submit(task, i)
#         # 产生res对象,对象有result方法
#         # pool 没有 join 方法,使用了res.result() 获取结果,会使多进程或者多线程阻塞
#         # print(res.result()) # main...20.27270380000118
#     pool.shutdown(wait=True)
# 	  #shutdown 关闭 进程池的入口,等待全部运行完 main...9.246424099997967
#     end = time.perf_counter()
#     # processes = [pool.submit(task,args = range(1,5)) for i in range(10)]
#     print(f'main...{end- start}') # main...45.25680309999734

标签:__,...,res,futures,concurrent,线程,模块,main,pool
From: https://www.cnblogs.com/mrsphere/p/17276689.html

相关文章

  • A模块练习题
    mysql练习题1.查找数据库版本号mysql>selectversion();2.查找数据库列表mysql>showtables;3.查看所有用户和权限,找到可以从任意IP地址访问mysql>showgrantsforroot@localhostmysql>selectdistinctconcat('user:''',user,'''@''',......
  • 关于python 的if __name__ == "__main__"的模块测试
    if__name__=="__main__"也就是说执行当前文件,不调用模块的时候__name__=__main__调用模块的时候,测试如下:1、新建test01.py文件测试代码如下print("这条消息来自test01")deffunc():print('hello,world!***')print("这条消息来自func")if__name__=="__......
  • ansible 常用模块 service
    模块说明Manageservices参数说明ParameterCommentsargumentsaliases:argsstring命令行上提供了其他参数。将远程主机与systemd一起使用时,此设置将被忽略。enabled boolean服务是否应在启动时启动。至少需要state和enabled中的......
  • ansible 常用模块 archive
    模块说明该unarchive模块解压缩存档。它不会解压缩不包含存档的压缩文件。默认情况下,它会在解包之前将源文件从本地系统复制到目标。设置remote_src=yes为解压缩目标上已存在的存档。在目标主机上需要zipinfo和gtar/unzip命令。需要目标主机上的zstd命令来展开.tar......
  • ansible 常用模块 user
    模块说明管理用户帐户和用户属性。此模块用于useradd创建、usermod修改和userdel删除帐户。参数ParameterCommentsappend boolean如果true,将用户添加到中指定的组groups。如果false,用户将只被添加到在指定的组中groups,将他们从所有其他组中删......
  • ansible 常用模块 group
    参数参数选项/默认值描述gidinterger 要为组设置的可选GID。localbooleanfalse ←(默认)true强制在实现它的平台上使用“local”命令替代项。这在要操作本地组时使用集中式身份验证的环境中非常有用。(例如,它使用代替lgroupaddgroupadd)。namestr......
  • DC-DC直流线性可调升压模块高压稳压输出电源5v12v24v48v转0-300V0-500V/0-600V/0-1000
    GRB系列非隔离宽电压输入高电压稳压输出特点 效率高达75%以上 1*2英寸标准封装 单电压输出 可直接焊在PCB上 工作温度:-40℃~+75℃ 阻燃封装,满足UL94-V0要求 温度特性好 电压控制输出,输出电压随控制电压的变化线应用GRB系列模块电源是一种DC-DC升压变换器。该模块电......
  • Flask框架 之使用蓝图实现模块划分
     一、示例代码run.pyfromappimportcreate_appif__name__=='__main__':app=create_app()app.run(debug=True,port=5000)__init__.pyfromflaskimportFlaskfromapp.controllersimportconfig_blueprintdefcreate_app():app=Fla......
  • 内核模块管理命令
    内核模块lsmod、insmod、rmmod、modinfo、modprobe等命令https://blog.csdn.net/bandaoyu/article/details/128582615......
  • [Python]异步concurrent.futures并发
    '''concurrent.futures模块提供异步执行可调用对象高层接口,使用线程池ThreadPoolExecutor或进程池ProcessPoolExecutor来实现异步。目的是保证服务稳定运行的前提下提供最大的并发能力。'''fromconcurrent.futuresimportFuturefromconcurrent.futuresimportThrea......