I am learning multiprocessing and running code I found somewhere on the website (I add print("check...")) to observe the sequence of code running with apply_async. Below is the code:
import multiprocessing
import time
def func(msg):
for i in range(3):
print(msg)
time.sleep(1)
if __name__ == "__main__":
pool = multiprocessing.Pool(processes=8)
for i in range(10):
msg = "hello %d" %(i)
pool.apply_async(func, (msg, ))
print('check whether block' + str(i))
print('check')
pool.close()
pool.join()
print("Sub-process(es) done.")
When I run it, I get the following output:
hello 0
hello 2
hello 4
hello 1
hello 3
hello 5
hello 6
hello 7
check whether block0
check whether block1
check whether block2
check whether block3
check whether block4
check whether block5
check whether block6
check whether block7
check whether block8
check whether block9
check
hello 0
hello 4
hello 1
hello 5
hello 2
hello 3
hello 6
hello 7
hello 4
hello 0
hello 6
hello 3
hello 5
hello 2
hello 7
hello 1
hello 8
hello 9
hello 9
hello 8
hello 9
hello 8
Sub-process(es) done.
But what I am hoping to see is the following:
hello 0
check whether block0
hello 2
check whether block2
hello 4
check whether block4
hello 1
check whether block1
hello 3
check whether block3
hello 5
check whether block5
hello 6
check whether block6
hello 7
check whether block7
hello 0
hello 4
hello 1
hello 5
hello 2
hello 3
hello 6
hello 7
hello 4
hello 0
hello 6
hello 3
hello 5
hello 2
hello 7
hello 1
hello 8
check whether block8
hello 9
check whether block9
hello 9
hello 8
hello 9
hello 8
check
Sub-process(es) done.
Basically I thought first 8 print('check whether...') should be executed following each pool.apply_async. And after 2 processes are freed up, 8 and 9 will be printed. And check is printed at the end. What I see seems to prove me wrong, but I don't know how exactly the sequence of codes is executed.
sys.stdout.flush()after printing and the output might be more to your liking.Pool's task manager.