I have a question regarding this code:
import time
from concurrent.futures import ProcessPoolExecutor
# SINGLE PROCESS
def ask_user():
start = time.time()
user_input = input('Enter your name: ')
greet = f'Hello, {user_input}'
print(greet)
print('ask_user: ', time.time() - start)
def complex_calculation():
print('Started calculating...')
start = time.time()
[x**2 for x in range(10)]
print('complex_calculation: ', time.time() - start)
# With a single thread, we can do one at a time—e.g.
start = time.time()
ask_user()
complex_calculation()
print('Single thread total time: ', time.time() - start, '
')
# TWO PROCESSES
# With two processes, we can do them both at once...
start = time.time()
if __name__ == '__main__':
with ProcessPoolExecutor(max_workers=2) as pool:
pool.submit(complex_calculation)
pool.submit(complex_calculation)
print('Two process total time: ', time.time() - start)
When I run it, it runs forever, but if I put all the code inside the condition block, then it works well:
import time
from concurrent.futures import ProcessPoolExecutor
# SINGLE PROCESS
def ask_user():
start = time.time()
user_input = input('Enter your name: ')
greet = f'Hello, {user_input}'
print(greet)
print('ask_user: ', time.time() - start)
def complex_calculation():
print('Started calculating...')
start = time.time()
[x**2 for x in range(10)]
print('complex_calculation: ', time.time() - start)
if __name__ == '__main__':
# With a single thread, we can do one at a time—e.g.
start = time.time()
ask_user()
complex_calculation()
print('Single thread total time: ', time.time() - start, '
')
# TWO PROCESSES
# With two processes, we can do them both at once...
start = time.time()
with ProcessPoolExecutor(max_workers=2) as pool:
pool.submit(complex_calculation)
pool.submit(complex_calculation)
print('Two process total time: ', time.time() - start)
I guess that it has something to do with how Python calls modules and recursion but I don't have much idea other than that, so my question is - why does the first code run forever and second doesn't?
question from:
https://stackoverflow.com/questions/65908870/program-running-forever-if-not-inside-the-condition 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…