Python在 os 模块中,对Linux的fork函数进行了封装,可以很简单的就创建了一个子进程:
1 2 3 4 5 6 7 8
import os
print'Process (%s) start...' % os.getpid() pid = os.fork() if pid==0: print'I am child process (%s) and my parent is %s.' % (os.getpid(), os.getppid()) else: print'I (%s) just created a child process (%s).' % (os.getpid(), pid)
if __name__=='__main__': print'Parent process %s.' % os.getpid() p = Process(target=run_proc, args=('test',)) print'Process will start.' p.start() p.join() print'Process end.'
执行结果如下:
1 2 3 4
Parent process 5928. Process will start. Run child process test (5929)... Process end.
进程池
如果需要大量的子进程,可以利用进程池的方法来批量创建子进程
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
from multiprocessing import Pool import os, time, random
if __name__=='__main__': print'Parent process %s.' % os.getpid() p = Pool() for i in range(5): p.apply_async(long_time_task, args=(i,)) print'Waiting for all subprocesses done...' p.close() p.join() print'All subprocesses done.'
执行结果如下:
1 2 3 4 5 6 7 8 9 10 11 12 13
Parent process 669. Waiting for all subprocesses done... Run task 0 (671)... Run task 1 (672)... Run task 2 (673)... Run task 3 (674)... Task 2 runs 0.14 seconds. Run task 4 (673)... Task 1 runs 0.27 seconds. Task 3 runs 0.86 seconds. Task 0 runs 1.41 seconds. Task 4 runs 1.91 seconds. All subprocesses done.
Pool 函数创建一个进程池,可以传入子进程的数量,默认使用 multiprocessing.cpu_count() 方法来获取CPU的核心数目,并以此创建子进程的数量
if __name__ == "__main__": pool = multiprocessing.Pool(processes=4) result = [] for i in xrange(3): msg = "hello %d" %(i) result.append(pool.apply_async(func, (msg, ))) pool.close() pool.join() for res in result: print":::", res.get() print"Sub-process(es) done."
执行结果:
1 2 3 4 5 6 7 8 9 10
msg: hello 0 msg: hello 1 msg: hello 2 end end end ::: donehello 0 ::: donehello 1 ::: donehello 2 Sub-process(es) done.