码迷,mamicode.com
首页 > 编程语言 > 详细

Python的并发并行[4] -> 并发 -> 利用线程池启动线程

时间:2018-01-01 16:51:23      阅读:184      评论:0      收藏:0      [点我收藏+]

标签:def   rom   gpo   exe   one   style   body   logs   start   

利用线程池启动线程


 

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 模块

 

Python的并发并行[4] -> 并发 -> 利用线程池启动线程

标签:def   rom   gpo   exe   one   style   body   logs   start   

原文地址:https://www.cnblogs.com/stacklike/p/8167128.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!