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

时间:2023-03-09 23:27:54
Python的并发并行[4] -> 并发[0] -> 利用线程池启动线程

利用线程池启动线程


submitmap启动线程

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

 from concurrent.futures import ThreadPoolExecutor as tpe
from concurrent.futures import ProcessPoolExecutor as ppe
from time import ctime, sleep
from random import randint def foo(x, name):
print('%s%d starting at' % (name, x), ctime())
sleep(randint(1, 7))
print('%s%d completed at' % (name, x), ctime()) # Use submit function
print('-----Using submit function-----')
#executor = tpe(7)
#with executor:
with tpe(7) as executor:
for i in range(5):
executor.submit(foo, i, 'No.') # Use map function
print('-----Using map function-----')
with tpe(7) as executor:
executor.map(foo, range(5), ['No_a.', 'No_b.', 'No_c.', 'No_d.', 'No_e.']) # TODO: Learn more about ProcessPoolExecutor
"""
with ppe(2) as executor:
executor.submit(foo, 1, 'No.')
"""

定义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

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

未完待续...

相关阅读


1. concurrent.future 模块