To
start a thread with a thread pool
Submit with the Map Start Thread
Use two different ways to start a thread, while using with context management to control the thread pool
1 fromConcurrent.futuresImportThreadpoolexecutor as TPE2 fromConcurrent.futuresImportProcesspoolexecutor as PPE3 fromTimeImportCTime, Sleep4 fromRandomImportRandint5 6 deffoo (x, name):7 Print('%s%d starting at'%(name, x), CTime ())8Sleep (Randint (1, 7))9 Print('%s%d completed at'%(name, x), CTime ())Ten One #Use submit function A Print('-----Using Submit Function-----') - #executor = TPE (7) - #With executor: theWith TPE (7) as executor: - forIinchRange (5): -Executor.submit (foo, I,'No.') - + #Use map function - Print('-----Using Map Function-----') +With TPE (7) as executor: AExecutor.map (foo, range (5), ['no_a.','No_b.','No_c.','no_d.','no_e.']) at - #Todo:learn more about Processpoolexecutor - """ - With PPE (2) as executor: - Executor.submit (foo, 1, ' No. ') - """
Define the Foo method and start the thread pool executor in two ways, where the with TPE (7) As executor statement is equivalent to Executor = TPE (), with executor, The context management of the with enables the executor to suspend waiting until all the submit Foo functions are complete.
Run to get results
-----Using Submit Function-----no.0 starting at Wed2 14:33:06 2017No.1 starting at Wed 2 14:33:06 2017No.2 starting at Wed 2 14:33:06 2017No.3 starting at Wed 2 14:33:06 2017No.4 starting at Wed 2 14:33:06 2017No.2 completed at Wed 2 14:33:07 2017no.0 completed at Wed2 14:33:08 2017No.3 completed at Wed 2 14:33:08 2017No.1 completed at Wed 2 14:33:09 2017No.4 completed at Wed 2 14:33:13-----Using Map Function-----no_a.0 starting at Wed2 14:33:13 2017No_b.1 starting at Wed 2 14:33:13 2017No_c.2 starting at Wed 2 14:33:13 2017no_d.3 starting at Wed 2 14:33:13 2017no_e.4 starting at Wed 2 14:33:13 2017No_b.1 completed at Wed 2 14:33:14 2017No_c.2 completed at Wed 2 14:33:14 2017no_d.3 completed at Wed 2 14:33:14 2017no_a.0 completed at Wed2 14:33:18 2017no_e.4 completed at Wed 2 14:33:18 2017
View Code
Viewing the results shows that the two effects are similar.
Not to be continued ...
Related reading
1. Concurrent.future Module
Python's concurrency parallel [4], concurrency--using the thread pool to start threads