zoukankan      html  css  js  c++  java
  • 线程池

    '''
    concurrent.futures 模块提供了高度封装的异步调用接口
    ThreadPoolExecutor :线程池,提供异步调用
    ProcessPoolExecutor:进程池,提供异步调用。
    基本方法:
    submit(fn,*args,**kargs) 异步提交任务

    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)
    取得结果

    add_done_callback(fn)
    回调函数

    '''
    import time
    from concurrent.futures import ThreadPoolExecutor
    def func(n):
    time.sleep(2)
    print(n)
    return n*n

    t= ThreadPoolExecutor(max_workers=5) #默认不要超过CUP个数的5倍
    t_lst=[]
    for i in range(20):
    t1 =t.submit(func,i)
    t_lst.append(t1)
    t.shutdown()
    print('主线程')
    for i in t_lst:
    print('***',i.result())
  • 相关阅读:
    python3内置函数大全
    字符串格式化及函数
    基础数据和编码
    python基本数据类型
    python基础
    python re模块
    python json模块
    python os模块
    python random模块
    python time模块
  • 原文地址:https://www.cnblogs.com/liu1983/p/13627491.html
Copyright © 2011-2022 走看看