为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

翻过高山走不出你 2023-09-12 17:38:24
该代码应该complex_calculation()在新进程上运行。但是当我执行代码时,一旦单线程完成,它就会重新启动整个程序,并且我必须再次输入输入(这意味着它从代码的开头重新启动,而不是只运行指定的函数)。我看的教程没有这个问题。当作者运行时,它不会像我得到的那样提示输入两次。使用 ProcessPoolExecutor 时也存在此问题。Pycharm版本:2020.2 Python版本:3.8这是代码:import timefrom multiprocessing import Processdef 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 functionprocess = Process(target=complex_calculation)process.start()start = time.time()process.join()print(f'Two process total time: {time.time() - start}')
查看完整描述

1 回答

?
慕标5832272

TA贡献1966条经验 获得超4个赞

您应该将代码更改为如下所示:


if __name__ == "__main__":

    start = time.time()

    ask_user()

    complex_calculation()

    ...    

根据文档,使用if __name__ == __main__:是必要的。

查看完整回答
反对 回复 2023-09-12
  • 1 回答
  • 0 关注
  • 93 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信