Why is the line "if __name __ ==" __ main__ "required for the multiprocessor billiards module?

If I have the following code:

def f():
    print 'ok!'
    import sys
    sys.exit()

if __name__=='__main__':
    import billiard
    billiard.forking_enable(0)
    p = billiard.Process( target=f)
    p.start()
    while p.is_alive():
        pass

      

The script behaves as expected by typing "ok!" and ends. But if I omit the line if __name__=='__main__':

and de-indent, the following lines, my machine (OS X) goes crazy, constantly generating a ton of Python processes, while I killall Python

. Any idea what's going on here?

(To mark this as a duplicate, note that while the other question asks the purpose if __name__=='__main__'

in general, I am specifically asking why abandoning use here results in unexpected behavior)

+3


source to share


1 answer


You disable support fork

with the line:

billiard.forking_enable(0)

      



This means that the library will need to create (instead of fork) a child process and re-import the module __main__

to run f

, as Windows does. Without a guard, if __name__ ...

re-importing a module __main__

into child objects also means re-running your code that creates billiard.Process

, which creates an infinite loop.

If you leave it fork

enabled, re-importing in the child process is unnecessary, so everything will work with if __name__ ...

or without protection .

+6


source







All Articles