该代码应该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 回答
![?](http://img1.sycdn.imooc.com/533e4c5600017c5b02010200-100-100.jpg)
慕标5832272
TA贡献1966条经验 获得超4个赞
您应该将代码更改为如下所示:
if __name__ == "__main__":
start = time.time()
ask_user()
complex_calculation()
...
根据文档,使用if __name__ == __main__:
是必要的。
添加回答
举报
0/150
提交
取消