ImportOSImportThreadingImportMultiprocessing#worker Functiondefworker (sign, lock): Lock.acquire ()Print(sign, os.getpid ()) lock.release ()if __name__=='__main__': Print('Main:', Os.getpid ())#multi-threadRecord =[] Lock=Threading. Lock () forIinchRange (5): Thread= Threading. Thread (target=worker,args= ('Thread', Lock)) Thread.Start () record.append (thread) forThreadinchRecord:thread.join ()#multi-processRecord =[] Lock=multiprocessing. Lock () forIinchRange (5): Process= multiprocessing. Process (target=worker,args= ('Process', Lock)) Process.Start () record.append (process) forProcessinchRecord:process.join ()
If you do not write if __name__ = = ' __main__ ': There will be countless processes that eventually occupy all memory reasons:
__name__ is a method that indicates how the current py file is called. If it is equal to "__main__" means to execute directly, if not, it is used to be called by another file, this time if is false, then it will not execute the outermost code.
In this case, when the child process loads the file, it calls the Processfunc function, which executes the code that generates the child process, because he is the outermost code, or global code, which produces multiple processes.
Python multi-process, process iterative creation, resulting in computer crashes problem solving