Why does this launch an infinite loop of new processes?

Ethan Furman ethan at stoneleaf.us
Wed Dec 21 14:29:43 EST 2011


Andrew Berg wrote:
> I am trying to understand the multiprocessing module, and I tried some
> simple code:
> 
> import multiprocessing
> def f():
> 	print('bla bla')
> p = multiprocessing.Process(target=f)
> p.start()
> p.join()
> 
> And the result is a new process that spawns a new process that spawns a
> new process ad infinitum until I log out and the OS forcefully
> terminates all my user processes. I have no idea what is happening; I
> expected it to just print the string and terminate.
> 

Anything that runs at import time should be protected by the `if 
__name__ == '__main__'` idiom as the children will import the __main__ 
module.


8<-----------------------------------------------
import multiprocessing
def f():
     print('bla bla')

if __name__ == '__main__':
     p = multiprocessing.Process(target=f)
     p.start()
     p.join()
8<-----------------------------------------------

~Ethan~



More information about the Python-list mailing list