0

I am new to multiprocessing in Python, and am following one of Cory Shaffer's tutorials.

I have written the exact same code as in his tutorial:

import time 
import multiprocessing


start = time.perf_counter() 

def do_something(seconds): 
    print(f"Sleeping for {seconds} seconds...")
    time.sleep(seconds)
    print("Done Sleeping")

processes = []

for _ in range(10): 
    p = multiprocessing.Process(target = do_something,args = [1.5])
    p.start() 
    processes.append(p)

for process in processes: 
    process.join()


finish = time.perf_counter() 

print(f'Finished in {round(finish-start,2)} seconds(s)')

However, when I run the above, I get the RunTime error:

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.

Any ideas why I am getting this, and how to solve it?

I found a similar question, but couldn't quite apply it to my code to make it work: RuntimeError on windows trying python multiprocessing

Thanks!

  • Put all the code that you do not want executed by your subprocesses, which is everything except the statement `import time` and the function definition for `do_something`, within a `if __name__ == '__main__':` block. Leaving `import multiprocessing` outside of that block will not hurt but is not required by your subprocesses. – Booboo Mar 17 '22 at 13:31
  • You might wish to read the **Explantion** section of [this answer](https://stackoverflow.com/questions/68644048/multiprocessing-issue-with-windows#answer-68650790) – Booboo Mar 17 '22 at 13:44

0 Answers0