• concurrent模块


    concurrent包

    concurrent.futrues模块

    3.2版本引入

    异步并行任务模块,提供一个高级的异步可执行的便利接口.

    提供了两个池执行器

    ThreadPoolExecutor异步调用的线程池的Executor

    ProcessPoolExecutor异步调用的进程池的Executor

    ThreadPoolExecutor对象

    首先需要定义一个池的执行器对象,Executor类子类对象

    方法 含义
    ThreadPoolExecutor(max_workers= 1) 池中最多创建max_workers个线程的池类同时异步执行,返回Executor实例
    submit(fn,*args,**kwargs) 异步提交执行的函数及其参数,返回Future实例
    shutdown(wait = True) 清理池
    from concurrent.futures import ProcessPoolExecutor, ThreadPoolExecutor
    import time
    
    # ProcessPoolExecutor(5)  # 5代表只能开启5个进程
    # ProcessPoolExecutor()  # 默认以CPU的个数限制进程数
    
    pool = ThreadPoolExecutor(5)  # 5代表只能开启5个线程 
    # ThreadPoolExecutor()  # 默认以CPU个数 * 5 限制线程数
    
    # t = Tread()  # 异步提交
    # t.start(0)
    

    Future类

    方法 含义
    result(timeout=None) 可以查看调用函数的返回值结果,tiime未none,一直等待返回;timeout设置到期,抛出concurrent.futures.TimeError异常
    done() 如果调用被成功的取消或者执行完成,返回True
    cancelled() 如果调用被成功的取消,返回True
    result() 如果正在运行且不能被取消,返回True
    cancel() 尝试取消调用,如果已经执行且不能取消放回false;否则返回True
    exception(timeout= None) 取返回的异常,timeout为None,一直等待返回;timeout设置到期,抛出concurrent.futures.TimeoutError异常
    #pip3 install gevent
    from gevent import monkey
    monkey.patch_all()  # 可以监听该程序下所有的IO操作
    import time
    from gevent import spawn, joinall  # 用于做切换 + 保存状态
    
    
    def func1():
        print('1')
        # IO操作
        time.sleep(1)
    
    
    def func2():
        print('2')
        time.sleep(3)
    
    
    def func3():
        print('3')
        time.sleep(5)
    
    
    start_time = time.time()
    
    s1 = spawn(func1)
    s2 = spawn(func2)
    s3 = spawn(func3)
    
    # s2.join()  # 发送信号,相当于等待自己 (在单线程的情况下)
    # s1.join()
    # s3.join()
    # 必须传序列类型
    joinall([s1, s2, s3])
    
    end_time = time.time()
    
    print(end_time - start_time)
    

    ProcessPoolExecutor对象

    跟线程方法一样,就是使用多进程完成.

    支持上下文管理

    concurrent.futrues.ProcessPoolExecutor继承自concurrent.futrues.base.Executor,

    支持上下文管理,可以使用with语句

    回调函数

    将一个函数的返回值直接传递给另一个函数

    # 回调函数
    def call_back(res):
        print(type(res))
        # 注意: 赋值操作不要与接收的res同名
        res2 = res.result()
        print(res2)
    
    
    for line in range(5):
        pool.submit(task, 1).add_done_callback(call_back)
    
    
    # 会让所有线程池的任务结束后,才往下执行代码
    # pool.shutdown()
    
    print('hello')
    

    总结

    这个库统一了线程池,进程池的调用,简化了编程

    唯一缺点:无法设置线程名称,无所吊谓

  • 相关阅读:
    高并发编程之基础概念
    使用JAXB实现Bean与Xml相互转换
    python语法(五)—函数
    2018年终总结
    python语法(四)— 文件操作
    excel开发
    spring 常用注解,@primary注解
    spring中InitializingBean和@Bean的初始化,bean初始化
    @PostConstruct 注解
    LocalDateTime java8
  • 原文地址:https://www.cnblogs.com/agsol/p/11733234.html
Copyright © 2020-2023  润新知