zoukankan      html  css  js  c++  java
  • python3 ThreadPoolExecutor

    code
    from concurrent.futures import ThreadPoolExecutor,ProcessPoolExecutor
    from threading import currentThread
    from multiprocessing import current_process
    import time,os
     
     
    def task(i):
        print(f'{currentThread().name} 在运行 任务{i}')
        print(f'{current_process().name} 在运行 任务{i}')
        time.sleep(0.2)
        return i**2
     
     
    if __name__ == '__main__':
        pool = ThreadPoolExecutor(4)
        fu_list = []
        for i in range(20):
            future = pool.submit(task,i)
            # print(future.result())  # 拿不到值会阻塞在这里。
            fu_list.append(future)
     
     
        pool.shutdown(wait=True)  # 等待池内所有任务执行完毕
        for i in fu_list:
            print(i.result())# 拿不到值会阻塞在这里。
    outputs
    macname@MacdeMacBook-Pro py % python3 cccccc.py
    ThreadPoolExecutor-0_0 在运行 任务0
    ThreadPoolExecutor-0_1 在运行 任务1
    MainProcess 在运行 任务1
    ThreadPoolExecutor-0_2 在运行 任务2
    ThreadPoolExecutor-0_3 在运行 任务3
    MainProcess 在运行 任务0
    MainProcess 在运行 任务2
    MainProcess 在运行 任务3
    ThreadPoolExecutor-0_1 在运行 任务4
    MainProcess 在运行 任务4
    ThreadPoolExecutor-0_0 在运行 任务5
    MainProcess 在运行 任务5
    ThreadPoolExecutor-0_3 在运行 任务7
    ThreadPoolExecutor-0_2 在运行 任务6
    MainProcess 在运行 任务7
    MainProcess 在运行 任务6
    ThreadPoolExecutor-0_1 在运行 任务8
    MainProcess 在运行 任务8
    ThreadPoolExecutor-0_0 在运行 任务9
    MainProcess 在运行 任务9
    ThreadPoolExecutor-0_2 在运行 任务11
    MainProcess 在运行 任务11
    ThreadPoolExecutor-0_3 在运行 任务10
    MainProcess 在运行 任务10
    ThreadPoolExecutor-0_0 在运行 任务12
    MainProcess 在运行 任务12
    ThreadPoolExecutor-0_3 在运行 任务13
    ThreadPoolExecutor-0_2 在运行 任务14
    MainProcess 在运行 任务13
    MainProcess 在运行 任务14
    ThreadPoolExecutor-0_1 在运行 任务15
    MainProcess 在运行 任务15
    ThreadPoolExecutor-0_0 在运行 任务16
    ThreadPoolExecutor-0_2 在运行 任务17
    MainProcess 在运行 任务16
    MainProcess 在运行 任务17
    ThreadPoolExecutor-0_3 在运行 任务18
    MainProcess 在运行 任务18
    ThreadPoolExecutor-0_1 在运行 任务19
    MainProcess 在运行 任务19
    0
    1
    4
    9
    16
    25
    36
    49
    64
    81
    100
    121
    144
    169
    196
    225
    256
    289
    324
    361
    macname@MacdeMacBook-Pro py %
     
     
     
     
     
     
     
     
     

  • 相关阅读:
    .Net中的加密解密
    C#集合类
    .NetFramework 1: I/O & Stream
    系列4:文件操作以及读写文件
    PetShop之表示层设计 :PetShop之表示层设计 (转)
    const和static readonly 区别
    ASP.NET经典源代码下载地址及数据库配置方法
    一个知名出版商的挫折——解读 Wrox 的历史、现在与未来(转载)
    《C++编程——数据结构与程序设计方法》程序范例:影碟店(源代码)
    ASP.NET 英语词典
  • 原文地址:https://www.cnblogs.com/sea-stream/p/14193579.html
Copyright © 2011-2022 走看看