Search code examples
pythonpython-3.xmultithreadingpython-multiprocessing

multiprocessing.Process() just stopped working


I was teaching myself about multiptocessing in Python on Spyder and was working through some relatively simple examples when it suddenly stopped working. Going back to some simpler examples that had previously worked they now seemed to be not working as well. I can't think what I could have done to make them stop working. Below is my code:

import time
import multiprocessing

start = time.perf_counter()

def do_something():
    print('Sleeping 1 second...')
    time.sleep(1)
    print('Done Sleeping...')


p1 = multiprocessing.Process(target = do_something)
p2 = multiprocessing.Process(target = do_something)

p1.start()
p2.start()

p1.join()
p2.join()


finish = time.perf_counter()


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

It just seems to run as if the middle part:

p1 = multiprocessing.Process(target = do_something)
p2 = multiprocessing.Process(target = do_something)

p1.start()
p2.start()

p1.join()
p2.join()

Is not there?

edit

The only output was

Finished in 0.64 second(s)

with no error message.


Solution

  • You need to read the error and follow the instruction !

    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.
    

    Please run the below code:

    import multiprocessing
    
    
    def worker(num):
        """Returns the string of interest"""
        return "worker %d" % num
    
    
    def main():
        pool = multiprocessing.Pool(4)
        results = pool.map(worker, range(10))
    
        pool.close()
        pool.join()
    
        for result in results:
            # prints the result string in the main process
            print(result)
    
    
    if __name__ == '__main__':
        # Better protect your main function when you use multiprocessing
        main()