[Tutor] Multiprocessing
Stephen M Smith
stephen.m.smith at comcast.net
Mon Sep 21 21:19:36 EDT 2020
I am trying to figure out how multiprocessing works for an application I
have. My methodology is to vigorously read everything I can find on the
subject including examples. I have found an example and modified it a bit.
Here is the code and it works:
import concurrent.futures
from multiprocessing import Process, freeze_support
import time
print("starting up")
def do_something(seconds):
print(f'Sleeping {seconds} second(s)')
time.sleep(1)
return f"done sleeping...{seconds} seconds"
if __name__ == '__main__':
print("about to go")
freeze_support()
# Process(target=do_something(1)).start
with concurrent.futures.ProcessPoolExecutor() as executor:
# f1 = executor.submit(do_something,1)
secs = [10,9,8,7,6,5,4,3,2,1]
results = [executor.submit(do_something, sec) for sec in secs]
for f in concurrent.futures.as_completed(results):
print(f.result())
What I don't get is the output, also pasted below. As you will see the
"starting up" message is displayed 17 times. I cannot begin to understand
how that statement is executed more than once and 17 times makes no sense
either. Thanks in advance for any insight you can provide.
starting up
about to go
starting up
starting up
starting up
starting up
Sleeping 10 second(s)
starting up
Sleeping 9 second(s)
starting up
Sleeping 8 second(s)
Sleeping 7 second(s)
starting up
starting up
Sleeping 6 second(s)
Sleeping 5 second(s)
starting up
starting up
Sleeping 4 second(s)
starting up
Sleeping 3 second(s)
Sleeping 2 second(s)
starting up
Sleeping 1 second(s)
starting up
starting up
starting up
starting up
done sleeping...10 seconds
done sleeping...9 seconds
done sleeping...8 seconds
done sleeping...5 seconds
done sleeping...4 seconds
done sleeping...7 seconds
done sleeping...6 seconds
done sleeping...3 seconds
done sleeping...2 seconds
done sleeping...1 seconds
Process finished with exit code 0
More information about the Tutor
mailing list