博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Python的并发并行[4] -> 并发[0] -> 利用线程池启动线程
阅读量:5142 次
发布时间:2019-06-13

本文共 2080 字,大约阅读时间需要 6 分钟。

利用线程池启动线程


 

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 function12 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 function20 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 ProcessPoolExecutor25 """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.

 

转载于:https://www.cnblogs.com/stacklike/p/8167128.html

你可能感兴趣的文章
【Nowcoder】玩游戏
查看>>
过滤器(Filter)
查看>>
字符串的操作
查看>>
性能优化之Java(Android)代码优化
查看>>
springMVC相关—文件上传
查看>>
由Oracle 11g SYSAUX 和 SYSTEM 表空间回收引发的联想
查看>>
uva 1416 Warfare And Logistics
查看>>
欲则不达
查看>>
盒子游戏
查看>>
OpenJudgeP1.10.08:病人排队__(刷题)_水题
查看>>
观察者模式
查看>>
Hadoop分布式文件系统中架构和设计要点汇总
查看>>
cout和printf
查看>>
UVa 10088 - Trees on My Island (pick定理)
查看>>
#C++PrimerPlus# Chapter11_Exersice4_mytimeV4
查看>>
iOS8 针对开发者所拥有的新特性汇总如下
查看>>
Jmeter + Grafana搭建实时监控可视化
查看>>
uCGUI字符串显示过程分析和uCGUI字库的组建
查看>>
h5唤起app
查看>>
SQL Server 2008 /SQL Server 2008 R2 配置数据库邮件
查看>>