zoukankan      html  css  js  c++  java
  • Python的并发并行[4] -> 并发[0] -> 利用线程池启动线程

    利用线程池启动线程


    submitmap启动线程

    利用两种方式分别启动线程,同时利用with上下文管理来对线程池进行控制

     1 from concurrent.futures import ThreadPoolExecutor as tpe
     2 from concurrent.futures import ProcessPoolExecutor as ppe
     3 from time import ctime, sleep
     4 from random import randint
     5 
     6 def foo(x, name):
     7     print('%s%d starting at' % (name, x), ctime())
     8     sleep(randint(1, 7))
     9     print('%s%d completed at' % (name, x), ctime())
    10 
    11 # Use submit function
    12 print('-----Using submit function-----')
    13 #executor = tpe(7)
    14 #with executor:
    15 with tpe(7) as executor:
    16     for i in range(5):
    17         executor.submit(foo, i, 'No.')
    18 
    19 # Use map function
    20 print('-----Using map function-----')
    21 with tpe(7) as executor:
    22     executor.map(foo, range(5), ['No_a.', 'No_b.', 'No_c.', 'No_d.', 'No_e.'])
    23 
    24 # TODO: Learn more about ProcessPoolExecutor
    25 """
    26 with ppe(2) as executor:
    27     executor.submit(foo, 1, 'No.')
    28 """

    定义foo方法,并运用两种方式启动线程池执行器,其中with tpe(7) as executor语句等价于executor = tpe(), with executor,with的上下文管理可以保证执行器在所有submit的foo函数完成之前挂起等待。

    运行得到结果

    -----Using submit function-----  
    No.0 starting at Wed Aug  2 14:33:06 2017  
    No.1 starting at Wed Aug  2 14:33:06 2017  
    No.2 starting at Wed Aug  2 14:33:06 2017  
    No.3 starting at Wed Aug  2 14:33:06 2017  
    No.4 starting at Wed Aug  2 14:33:06 2017  
    No.2 completed at Wed Aug  2 14:33:07 2017  
    No.0 completed at Wed Aug  2 14:33:08 2017  
    No.3 completed at Wed Aug  2 14:33:08 2017  
    No.1 completed at Wed Aug  2 14:33:09 2017  
    No.4 completed at Wed Aug  2 14:33:13 2017  
    -----Using map function-----  
    No_a.0 starting at Wed Aug  2 14:33:13 2017  
    No_b.1 starting at Wed Aug  2 14:33:13 2017  
    No_c.2 starting at Wed Aug  2 14:33:13 2017  
    No_d.3 starting at Wed Aug  2 14:33:13 2017  
    No_e.4 starting at Wed Aug  2 14:33:13 2017  
    No_b.1 completed at Wed Aug  2 14:33:14 2017  
    No_c.2 completed at Wed Aug  2 14:33:14 2017  
    No_d.3 completed at Wed Aug  2 14:33:14 2017  
    No_a.0 completed at Wed Aug  2 14:33:18 2017  
    No_e.4 completed at Wed Aug  2 14:33:18 2017  
    View Code

    查看结果可以看出,两者效果相近。

    未完待续...

    相关阅读 


    1. concurrent.future 模块

  • 相关阅读:
    loadrunner12-参数化以及参数化关联
    loadrunner--vugen录制脚本提示“无Internet访问。您可能无法录制并执行业务进程”
    loadrunner--web_url函数用法
    loadrunner12-用Chrome如何录制脚本
    LoadRunner--Analysis各项指标详解
    Windows Error Code(windows错误代码详解)
    CentOS 7 (Linux) 下载百度网盘大文件
    博客园cnblogs:自定义页面风格
    Windows Server 2003 添加“Resin”到“服务”出错
    转:mysql分页原理和高效率的mysql分页查询语句
  • 原文地址:https://www.cnblogs.com/stacklike/p/8167128.html
Copyright © 2011-2022 走看看