多处理从代码的开头重新开始,而不是 运行 一个特定的函数
Multiprocessing restarts from beginning of the code instead running a specific function
代码应该 运行 complex_calculation()
在新进程上。但是当我执行代码时,一旦单线程完成,它就会重新启动整个程序,我必须再次输入(这意味着它从代码的开头重新启动,而不是仅仅 运行ning 指定的函数) .
我看的教程没有这个问题。当作者 运行s 时,它不会像我一样提示输入两次。
使用 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}')
代码应该 运行 complex_calculation()
在新进程上。但是当我执行代码时,一旦单线程完成,它就会重新启动整个程序,我必须再次输入(这意味着它从代码的开头重新启动,而不是仅仅 运行ning 指定的函数) .
我看的教程没有这个问题。当作者 运行s 时,它不会像我一样提示输入两次。
使用 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}')