1 #-*-coding:utf-8-*-2 fromMultiprocessingImportPool3 ImportOs,time,random4 5 defLong_time_task (name):6 Print 'Run Task Name%s and PID:%s.'%(Name,os.getpid ())7Start =time.time ()8Time.sleep (Random.random ())9End =time.time ()Ten Print 'Task%s Betwine%s'% (name, (end-start)) One #Pass A if __name__=='__main__': - Print 'Parent process%s.'%os.getpid () -p=Pool () the forIinchRange (5): - Print 'Now I am' andI - Print 'Parent process%s.'%os.getpid () -P.apply_async (long_time_task,args=(i,)) + Print 'Wait for all subprocesses-done ...' - Print(i,) + p.close () A P.join () at Print ' all over'
Result (Class):
Parent process 3896.
0
Parent process 3896.
1
Parent process 3896.
2
Parent process 3896.
3
Parent process 3896.
4
Parent process 3896.
Wait for all subprocesses-done ...
(4,)
Run Task Name 0 and pid:4300.
Run Task Name 1 and pid:4596.
Task 1 Betwine 1.32100009918
Run Task Name 2 and pid:4596.
Task 0 Betwine 2.61500000954
Run Task Name 3 and pid:4300.
Task 2 Betwine 2.65400004387
Run Task Name 4 and pid:4596.
Task 4 Betwine 0.599999904633
Task 3 Betwine 2.77799987793
All over
Python Process Pool