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

    1、新模块

    from concurrent.futures import ThreadPoolExecutor
    from concurrent.futures import ProcessPoolExecutor

    2、方法

    """
    线程数量一般是cpu个数*5
    submit(函数名, 参数)
    map(函数名, 可迭代对象)
    obj.shutdown() 相当于obj.close()和obj.join()
    obj.result()    获取返回值
    and_done_callback(函数),回调函数
    done() 查看某个线程是否完成
    """

    3、示例

    import time
    from concurrent.futures import ThreadPoolExecutor
    
    
    def test1(n):
        time.sleep(0.5)
        print(n)
        return pow(n, 2)
    
    
    t_pool = ThreadPoolExecutor(5)  # 线程池中线程的数量
    t_li = []
    for i in range(12):
        ret = t_pool.submit(test1, i) # 异步
        # print(ret.result())
        t_li.append(ret)
    t_pool.shutdown()   # 相当于close()和join()方法
    print('adaf')
    for t in t_li: 
        print('***', t.result())
    import time
    from concurrent.futures import ThreadPoolExecutor
    
    
    def test1(n):
        time.sleep(0.5)
        # print(n)
        return pow(n, 2)
    
    
    def test2(m):
        print(m.result())
    
    
    t_pool = ThreadPoolExecutor(5)  # 线程池中线程的数量
    t_li = []
    for i in range(12):
        t_pool.submit(test1, i).add_done_callback(test2)    # 回调函数
    import time
    from concurrent.futures import ThreadPoolExecutor
    
    
    def test1(n):
        time.sleep(0.5)
        print(n)
        return pow(n, 2)
    
    
    t_pool = ThreadPoolExecutor(5)  # 线程池中线程的数量
    t_pool.map(test1, range(6))     # map()异步
  • 相关阅读:
    [HEOI2015]兔子与樱花
    [HNOI2015]亚瑟王
    [JSOI2011]分特产
    某考试 T3 sine
    [JSOI2015]最小表示
    51NOD 1258 序列求和 V4
    Codeforces 622F The Sum of the k-th Powers
    Loj #6261. 一个人的高三楼
    [HAOI????] 硬币购物
    bzoj4318 OSU!
  • 原文地址:https://www.cnblogs.com/wt7018/p/11069738.html
Copyright © 2011-2022 走看看