zoukankan      html  css  js  c++  java
  • Python程序中的线程操作-concurrent模块

    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 = ProcessPoolExecutor(4)
        fu_list = []
        for i in range(10):
            future = pool.submit(task,i)
            print(future.result())  # 拿不到值会阻塞在这里。
            fu_list.append(future)
     
        pool.shutdown(wait=True)  # 等待池内所有任务执行完毕
        print("*"*20)
     
        for i in fu_list:
            print(i.result())# 拿不到值会阻塞在这里。
    Outputs
    macname@MacdeMacBook-Pro py % python3 cccccc.py
    MainThread 在运行 任务0
    ForkProcess-1 在运行 任务0
    0
    MainThread 在运行 任务1
    ForkProcess-2 在运行 任务1
    1
    MainThread 在运行 任务2
    ForkProcess-3 在运行 任务2
    4
    MainThread 在运行 任务3
    ForkProcess-4 在运行 任务3
    9
    MainThread 在运行 任务4
    ForkProcess-1 在运行 任务4
    16
    MainThread 在运行 任务5
    ForkProcess-2 在运行 任务5
    25
    MainThread 在运行 任务6
    ForkProcess-3 在运行 任务6
    36
    MainThread 在运行 任务7
    ForkProcess-4 在运行 任务7
    49
    MainThread 在运行 任务8
    ForkProcess-1 在运行 任务8
    64
    MainThread 在运行 任务9
    ForkProcess-2 在运行 任务9
    81
    ********************
    0
    1
    4
    9
    16
    25
    36
    49
    64
    81
    macname@MacdeMacBook-Pro py %
     
     
     
     
     
     
     
     
     
     

  • 相关阅读:
    govendor用法
    java.util.DualPivotQuickSort的实现
    windows注册表
    一道正则表达式题目
    JDK10、JDK11、JDK12新特性
    初夏清晨有所思
    Java 9新特性
    sklearn聚类评价指标
    沉浸式和全局式
    [抄]外部奖励对内在动机的侵蚀
  • 原文地址:https://www.cnblogs.com/sea-stream/p/14193682.html
Copyright © 2011-2022 走看看