The problem of code location for Python to create process pool

from multiprocessing import Pool
import time
import os
import random

**p = Pool(3)**

def worker(msg):
    start_time = time.time()
    print(" %d ----- %s" % (msg, os.getpid()))
    time.sleep(random.random()*2)
    stop_time = time.time()
    print(msg, " %0.2f"% (stop_time-start_time))



for i in range(0,10):
    p.apply_async(worker, (i,))

print("-----start-----")

p.close()
p.join()

print("------END-------")
< hr >

Why does the program report an error if p = pool (3) is written on def worker (msg)? If you write it under def worker (msg), it will work normally, and you can"t find the answer on the Internet. Please ask God for an answer. Thank you.

Mar.20,2022

I don't think it's the position defined by p, if the error is:

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.

then modify it like this.

  https://stackoverflow.com/que.

Menu