zoukankan      html  css  js  c++  java
  • Python标准模块_concurrent.futures

    介绍:

    concurrent.futures模块提供了高度封装的异步调用接口

    ThreadPoolExecutor:线程池,提供异步调用
    ProcessPoolExecutor:进程池,提供异步调用

    基本方法:
    submit(fn,*args,**kwargs)  异步提交任务

    map(func,*iterables,timeout=NOne,chunksize=1)渠道for循环submit的操作

    shutdown(wait=True)相当于进程池的pool.close()+pool.join()操作

    wait = True 等待池内所有任务执行完毕回收资源后才继续

    wait = False 立即返回,并不会等待池内的任务执行完毕

    但不管wait参数为何值,整个程序都会等到所有任务执行完毕

    submit和map必须在shutdown之前

    result(timeout=None)取得结果  相当于ret.get() 和ret.result()

    add_done_callback(fn)回调函数 callback = fn

    如何利用concurrent.futures模块开启线程池:

    import time
    from threading import currentThread
    from concurrent.futures import ThreadPoolExecutor  # 将ThreadPoolExecutor改成ProcessPoolExecutor就开启了多进程
    
    
    def func(i):
        time.sleep(1)
        print('子线程',i,currentThread().ident)  # 打印线程id
    return i**2
    tp = ThreadPoolExecutor(5) # 开启一个线程池里边有5个线程 for i in range(20): # 二十个任务 ret_l = [] # 弄个空列表准备装ret ret = tp.submit(func,i) # 用ret接收一下返回值 ret_l.append(ret) # 将ret放到ret_l中 for ret in ret_l: # 遍历ret_l print(ret.result()) # 打印返回值,注意这里的接口是result() tp.shutdown() # 关闭线程池

    使用map开启线程池:

    import time
    from threading import currentThread
    from concurrent.futures import ThreadPoolExecutor
    
    def func(i):
        time.sleep(1)
        print('子线程',i,currentThread().ident)
    
    tp = ThreadPoolExecutor(5)
    tp.map(func,range(20))

    回调函数:

    import time
    from threading import currentThread
    from concurrent.futures import ThreadPoolExecutor  # 将ThreadPoolExecutor改成ProcessPoolExecutor就开启了多进程
    
    
    def func(i):
        time.sleep(1)
        print('子线程',i,currentThread().ident)  # 打印线程id
        return i ** 2
    
    def call_back(ret):  # 回调函数
        print(ret.result())  # 打印返回值
    
    tp = ThreadPoolExecutor(5)  # 开启一个线程池里边有5个线程
    
    for i in range(20):  # 二十个任务
        ret = tp.submit(func,i).add_done_callback(call_back)  # 用ret接收一下返回值
       
    
    tp.shutdown()  # 关闭线程池
  • 相关阅读:
    访问HTML可以,访问PHPfile not found
    查看php-fpm的进程和端口号
    nginx调用PHP有sock方式和端口方式
    Linux创建用户、设置密码、修改用户、删除用户命令
    CentOS7 添加FTP用户并设置权限
    PHP使用文件锁解决高并发问题示例
    Huge CSV and XML Files in Python, Error: field larger than field limit (131072)
    怎样查询房产证是否抵押
    Python中模拟enum枚举类型的5种方法分享
    git for windows+TortoiseGit客户端的使用
  • 原文地址:https://www.cnblogs.com/gzying-01/p/10384694.html
Copyright © 2011-2022 走看看