該代碼應(yīng)該complex_calculation()在新進程上運行。但是當我執(zhí)行代碼時,一旦單線程完成,它就會重新啟動整個程序,并且我必須再次輸入輸入(這意味著它從代碼的開頭重新啟動,而不是只運行指定的函數(shù))。我看的教程沒有這個問題。當作者運行時,它不會像我得到的那樣提示輸入兩次。使用 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條經(jīng)驗 獲得超4個贊
您應(yīng)該將代碼更改為如下所示:
if __name__ == "__main__":
? ? start = time.time()
? ? ask_user()
? ? complex_calculation()
? ? ...? ??
根據(jù)文檔,使用if __name__ == __main__:
是必要的。
添加回答
舉報
0/150
提交
取消