5
def sample():
    pass

Process(target=sample).start()
Process(target=sample).start()

The above code fails with an error:

An attempt has been made to start a new process before the current process has finished its bootstrapping phase. This probably means that you are not using fork to start your child processes and you have forgotten to use the proper idiom in the main module

But this code runs fine:

def sample():
    pass
if __name__ == '__main__':
    Process(target=sample).start()
    Process(target=sample).start()

Why does the main module affect my code execution in this case? I am unable to understand the error message properly.

Note: I went through What does if __name__ == "__main__": do? but could not understand its relevance to my code.

Community
  • 1
  • 1
codingsplash
  • 4,785
  • 12
  • 51
  • 90

1 Answers1

10

When you create a new child process, the child process might (mostly depending on the OS you are using) re-import the current module.

In your case, re-importing the module also executes these two lines:

Process(target=sample).start()
Process(target=sample).start()

and what happens is, what the error message tells you:

An attempt has been made to start a new process before the current process has finished its bootstrapping phase. This probably means that you are not using fork to start your child processes and you have forgotten to use the proper idiom in the main module

While setting up the proper environment for your first child process, the code tries to fork off another child process. The manager detects this and tells you that this is not okay.

if __name__ == '__main__':
    Process(target=sample).start()
    Process(target=sample).start()

is a guard condition that allows the current module to be imported in the child module without this problem, because only the --well-- main module's name is __main__.

dhke
  • 15,008
  • 2
  • 39
  • 56
  • so it is not possible to code within juputer notebook ? is there any way to adopt using the notebook ? – Areza Mar 19 '21 at 11:42