zoukankan      html  css  js  c++  java
  • python_并发编程——线程池

    1.线程池

    import time
    from concurrent.futures import ThreadPoolExecutor
    
    
    def func(n):
        time.sleep(2)
        print(n)
    
    
    t_pool = ThreadPoolExecutor(max_workers=5)  # 创建线程池对象,设置线程池大小,建议不超过cpu数*5
    for i in range(20):
        t_pool.submit(func,i)    # 启动进程池,(执行的函数,传递的参数)

    结果:每过两秒钟随机打印5个数。

    import time
    from concurrent.futures import ThreadPoolExecutor
    
    
    def func(n):
        time.sleep(2)
        print(n)
    
    
    t_pool = ThreadPoolExecutor(max_workers=5)  # 创建线程池对象,设置线程池大小,建议不超过cpu数*5
    for i in range(20):
        t_pool.submit(func,i)    # 启动进程池,(执行的函数,传递的参数)
    t_pool.shutdown()  # 线程池被执行完,才会执行主线程的内容。
    print('主线程!')

    结果:

    2.取出线程池中函数的返回值

    from concurrent.futures import ThreadPoolExecutor
    
    
    def func(n):
        return n*n
    
    
    t_pool = ThreadPoolExecutor(max_workers=5)  # 创建线程池对象,设置线程池大小,建议不超过cpu数*5
    t_list = []
    for i in range(20):
        # 接收进程池的返回值
        t = t_pool.submit(func,i)
        # 将返回值添加进列表
        t_list.append(t)
    t_pool.shutdown()  # 线程池被执行完,才会执行主线程的内容。
    print('主线程!')
    for i in t_list:
        print(i.result())  # 用result方法,打印列表中的值

    结果:

     3.进程池

      导入ProcessPoolExecutor模块,方法和线程池一样。

    4.map()方法:

    from concurrent.futures import ThreadPoolExecutor
    import time
    
    
    def func(n):
        time.sleep(2)
        print(n)
    
    
    t_pool = ThreadPoolExecutor(max_workers=5)  # 创建线程池对象,设置线程池大小,建议不超过cpu数*5
    t_pool.map(func,range(20))    # 启动进程池,(执行的函数,传递的参数(可迭代的))

    结果:每过两秒钟随机打印5个数。map方法无法拿到函数的返回值。

    5.回调函数

    from concurrent.futures import ThreadPoolExecutor
    
    
    def func(n):
        return n*n
    
    
    def call_back(m):
        print('回调函数:',m.result())  # m是一个对象,需要用result方法,才能得到值
    
    
    t_pool = ThreadPoolExecutor(max_workers=5)
    t_pool.submit(func,5).add_done_callback(call_back)  # 回调函数(回调函数的函数名)

    结果:

     

  • 相关阅读:
    leetcode 350. Intersection of Two Arrays II
    leetcode 278. First Bad Version
    leetcode 34. Find First and Last Position of Element in Sorted Array
    leetcode 54. Spiral Matrix
    leetcode 59. Spiral Matrix II
    leetcode 44. Wildcard Matching
    leetcode 10. Regular Expression Matching(正则表达式匹配)
    leetcode 174. Dungeon Game (地下城游戏)
    leetcode 36. Valid Sudoku
    Angular Elements
  • 原文地址:https://www.cnblogs.com/wangdianchao/p/12141665.html
Copyright © 2011-2022 走看看