• 线程池-The End


    线程池-The End

    线程池介绍

    线程池是一个全新的模块-- from concurrent.futures import ThreadPoolExecutor

    concurrent.futures模块提供了高度封装的异步调用接口
    ThreadPoolExecutor:线程池,提供异步调用
    ProcessPoolExecutor: 进程池,提供异步调用
    

    线程池与进程池的用法完全一样,提供的接口也是完全一致的

    线程池不提供同步提交任务的方法,只有异步提交
    submit()

    shutdown(wait) 相当于进程池的pool.close + pool.join()的操作
    wait = True 等待池内所有任务执行完毕回收玩资源后才继续
    wait = False 立即返回,并不会等待池内的任务执行完毕

    submit 和 map 必须在shutdown之前

    map 拿不到返回值

    result() 取结果

    add_done_callback(fn) 回调函数

    import time
    from concurrent.futures import ThreadPoolExecutor
    
    def func(n):
        time.sleep(1)
        print(f'[{n}]',end='	')
        return n*n
    
    tp = ThreadPoolExecutor(max_workers=3)
    
    for i in range(1,22):
        t = tp.submit(func,i)
        print(f'{i}的幂为:',t.result(),end='	')
        if i %3 == 0:
            print()
    tp.shutdown() # 相当于close+join  没有shutdown会更高效
    print()
    print('所有子进程结束!')
    
    '''
    [1]	1的幂为: 1		[2]	2的幂为: 4		[3]	3的幂为: 9	
    [4]	4的幂为: 16	[5]	5的幂为: 25	[6]	6的幂为: 36	
    [7]	7的幂为: 49	[8]	8的幂为: 64	[9]	9的幂为: 81	
    [10]	10的幂为: 100	[11]	11的幂为: 121	[12]	12的幂为: 144	
    [13]	13的幂为: 169	[14]	14的幂为: 196	[15]	15的幂为: 225	
    [16]	16的幂为: 256	[17]	17的幂为: 289	[18]	18的幂为: 324	
    [19]	19的幂为: 361	[20]	20的幂为: 400	[21]	21的幂为: 441	
    
    所有子进程结束!
    '''
    

    回调函数

    import time
    from concurrent.futures import ThreadPoolExecutor
    
    def func(n):
        time.sleep(1)
        return n*n
    
    def task(m):
        print(f'******{m.result()}*******')
    
    tp = ThreadPoolExecutor(max_workers=3)
    
    for i in range(3):
        tp.submit(func,i).add_done_callback(task)
        
    '''
    ******0*******
    ******1*******
    ******4*******
    '''
    
  • 相关阅读:
    700. Search in a Binary Search Tree
    100. Same Tree
    543. Diameter of Binary Tree
    257. Binary Tree Paths
    572. Subtree of Another Tree
    226. Invert Binary Tree
    104. Maximum Depth of Binary Tree
    1、解决sublime打开文档,出现中文乱码问题
    移植seetafaceengine-master、opencv到ARM板
    ubuntu16.04-交叉编译-SeetaFaceEngine-master
  • 原文地址:https://www.cnblogs.com/dadazunzhe/p/11545541.html
Copyright © 2020-2023  润新知