0

I have code like this in a "foo.py":

# -*- coding: utf-8 -*-

import multiprocessing as mp

def foo():
    return 2

ctx = mp.get_context("forkserver")
process = ctx.Process(target=foo, args=())
process.start()

if I run python foo.py, it will raise Exception like this:

    raise RuntimeError('''
RuntimeError:
        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:

            if __name__ == '__main__':
                freeze_support()
                ...

        The "freeze_support()" line can be omitted if the program
        is not going to be frozen to produce an executable.

I do know how to avoid this, if I change to like this:

import multiprocessing as mp

def foo():
    return 2

if __name__ == "__main__":
    ctx = mp.get_context("forkserver")
    process = ctx.Process(target=foo, args=())
    process.start()

It works fine, but I want to know why should I need to put code to main block? what freeze_support means?

python==3.8.5
roger
  • 9,063
  • 20
  • 72
  • 119
  • 1
    To answer "why should I need to put code to main block?": https://stackoverflow.com/a/66696142/6744133. To answer "what freeze_support means?": https://docs.python.org/3/library/multiprocessing.html#multiprocessing.freeze_support – Oli Dec 06 '21 at 02:05

0 Answers0