Search code examples
pythonpython-multiprocessing

Multiprocessing restarts from beginning of the code instead running a specific function


The code should run complex_calculation() on a new process. But when I execute the code, once the single thread is complete, it restarts the whole program and I have to enter input again (which means it's restarting from the beginning of the code instead of just running the specified function).

The tutorial I'm watching doesn't have this problem. When author runs it doesn't prompt for input twice like I get.

The issue is also present when using ProcessPoolExecutor.

Pycharm version : 2020.2 Python version : 3.8

Here is the code:

import time
from multiprocessing import Process


def ask_user():
    start = time.time()
    user_input = input('Enter your name: ')
    greet = f'Hello, {user_input}'
    print(greet)
    print(f'ask_user, {time.time() - start}')


def complex_calculation():
    start = time.time()
    print('Started calculating..')
    [x**2 for x in range(20000000)]
    print(f'complex_calculation, {time.time() - start}')


start = time.time()
ask_user()
complex_calculation()
print(f'Single thread total time: {time.time() - start}')

# Start a new process to run complex_calculation function

process = Process(target=complex_calculation)
process.start()
start = time.time()
process.join()
print(f'Two process total time: {time.time() - start}')

Solution

  • You should change your code to something like this:

    if __name__ == "__main__":
        start = time.time()
        ask_user()
        complex_calculation()
        ...    
    

    According to the docs, using if __name__ == __main__: is necessary.

    See here, here, and also here