该代码应该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}')
慕标5832272
相关分类