Let's say I tested the following code to see the sub process pool act:
# coding=utf-8
import os
import sys
from multiprocessing import Pool
import time
import random
def run_proc(param1):
print("child procees %s pid is %s,parent id is %s" %
(param1, os.getpid(), os.getppid()))
starttime = time.time()
time.sleep(random.random() * 3)
endtime = time.time()
print('child process %s runs %0.2f seconds.' %
(param1, (endtime - starttime)))
if __name__ == '__main__':
print(sys.version)
pname = sys.argv[0].split('/')[-1]
print("process %s is running now...,it's pid is %s" % (pname, os.getpid()))
p = Pool(5)
for i in range(5):
p.apply_async(run_proc, args=("test"+str(i),))
print("waiting for all subprocess to end...")
p.close()
p.join()
print("all subprocesses are over!")
And that the output was all that I expected:
3.5.0 (default, Jul 23 2017, 10:55:33)
[GCC 4.2.1 Compatible Apple LLVM 8.1.0 (clang-802.0.42)]
process mp_basic_pool.py is running now...,it's pid is 19352
waiting for all subprocess to end...
child procees test0 pid is 19367,parent id is 19352
child procees test1 pid is 19368,parent id is 19352
child procees test2 pid is 19369,parent id is 19352
child procees test3 pid is 19370,parent id is 19352
child procees test4 pid is 19371,parent id is 19352
child process test2 runs 0.93 seconds.
child process test4 runs 1.33 seconds.
child process test3 runs 1.68 seconds.
child process test0 runs 2.68 seconds.
child process test1 runs 2.90 seconds.
all subprocesses are over!
[Finished in 3.2s]
There is the line "p.apply_async(run_proc, args=("test"+str(i),))"
. When I first wrote this code, I wrote it as: "p.apply_async(run_proc, args=("test"+str(i)))"
. A comma left, but the output was as:
3.5.0 (default, Jul 23 2017, 10:55:33)
[GCC 4.2.1 Compatible Apple LLVM 8.1.0 (clang-802.0.42)]
process mp_basic_pool.py is running now...,it's pid is 19382
waiting for all subprocess to end...
all subprocesses are over!
[Finished in 0.4s]
I looked for the python document and found that the second parameter should be a tuple, but is the comma be needed?