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 %
     
     
     
     
     
     
     
     
     

  • 相关阅读:
    delphi shr和shl的作用
    delphi socket 编程 使用多线程
    mysql 移除服务,并在cmd下切换目录
    delphi 结构体和TList的用法
    delphi 使用工控机控件 iThreadTimes 出现问题, 导致主程序创建页面的时候, 阻塞消息, 不能正常执行。
    Unicode 和 UTF-8 的区别
    Python 模块 re (Regular Expression)
    Python的函数式编程
    反向解析与PTR(Pointer Record)
    simhash算法
  • 原文地址:https://www.cnblogs.com/sea-stream/p/14193579.html
Copyright © 2011-2022 走看看