There are some problems with learning Python on the website of Liao Xuefeng:
In the process, when the parent process creates a child process, it is found that the display is not displayed in order, in question?
The reference code is as follows:
1 fromMultiprocessingImportPool2 ImportOS, time, Random3 4 defLong_time_task (name):5 Print 'Run Task%s (%s) ...'%(name, Os.getpid ())6Start =time.time ()7Time.sleep (Random.random () * 3)8End =time.time ()9 Print 'Task%s runs%0.2f seconds.'% (name, (End-start))Ten One if __name__=='__main__': A Print 'Parent process%s.'%os.getpid () -p =Pool () - forIinchRange (5): theP.apply_async (Long_time_task, args=(i,)) - Print 'waiting-subprocesses done ...' - p.close () - P.join () + Print 'All subprocesses is done .'
Operation Result:
It can be seen that code execution is performed from if __name__== ' __main__ ', after executing 15 lines of call Long_time_task, without printing 'Run task%s ' (%s) ... '.
But in line 15 P.apply_async (Long_time_task, args=(i,)), add print '?? ', will be in ' waiting for allsubprocesses ... ', before, print '?? "Very confused about this."
Modify the code so that each print time is printed:
1 fromMultiprocessingImportPool2 ImportOS, time, Random3 4 defLong_time_task (name):5 Print 'Run Task%s (%s) at%f ...'%(name, Os.getpid (), Time.time ())6Start =time.time ()7Time.sleep (Random.random () * 3)8End =time.time ()9 Print 'Task%s runs%0.2f seconds.'% (name, (End-start))Ten One if __name__=='__main__': A Print 'Parent process%s.'%os.getpid () -p =Pool () - forIinchRange (5): theP.apply_async (Long_time_task, args=(i,)) - Print ' time:%s: '%time.time () - Print 'Parent:%f'%time.time () - Print 'waiting-subprocesses done ...' + p.close () - P.join () + Print 'All subprocesses is done .' A
Operation Result:
This will find the reason:
PS: In the new code, the original code in Long_time_task () creates a child process in which sleep is deleted.
The parent runs first, when the child process is called, the child process is created, and then the post code is executed, and the child process is displayed when the child process is created.
That is, the child process creation takes time , at this idle time, the parent thread continues to execute the code, and the child process is created and displayed .
Python multi-process startup and code execution sequence