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 %
     
     
     
     
     
     
     
     
     

  • 相关阅读:
    css3 练习
    onethink 返回上一页
    小程序之轮播图
    Node 基本使用
    IDEA Terminal
    Spring Shell简单应用
    Spring Theme简单应用
    Spring MVC的学习笔记
    Win10出现键盘未失灵,按下的键都是快捷键的问题
    SQL Server 添加描述
  • 原文地址:https://www.cnblogs.com/sea-stream/p/14193579.html
Copyright © 2011-2022 走看看