多处理从代码开头重新启动,而不是运行特定函数

该代码应该complex_calculation()在新进程上运行。但是当我执行代码时,一旦单线程完成,它就会重新启动整个程序,并且我必须再次输入输入(这意味着它从代码的开头重新启动,而不是只运行指定的函数)。


我看的教程没有这个问题。当作者运行时,它不会像我得到的那样提示输入两次。


使用 ProcessPoolExecutor 时也存在此问题。


Pycharm版本:2020.2 Python版本:3.8


这是代码:


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}')


翻过高山走不出你
浏览 94回答 1
1回答

慕标5832272

您应该将代码更改为如下所示:if __name__ == "__main__":    start = time.time()    ask_user()    complex_calculation()    ...    根据文档,使用if __name__ == __main__:是必要的。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python