Python的并发并行[4] -> 并发[0] -> 利用线程池启动线程
利用线程池启动线程
submit与map启动线程
利用两种方式分别启动线程,同时利用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
查看结果可以看出,两者效果相近。
未完待续...
相关阅读