print('Process (%s) start...' % os.getpid()) # Only works on Unix/Linux/Mac: 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))
执行结果:
1 2 3
Process (63034) start... I (63034) just created a child process (63035). I am child process (63035) and my parent is 63034.
#子进程要执行的代码 defrun_proc(name): print('Run child process %s (%s).' % (name,os.getpid()))
if __name__ == '__main__': print('Parent process %s.' % os.getpid()) #创建子进程 p = Process(target=run_proc, args=('test',)) print('Child process will start') #开始启动子进程 p.start() #join()方法可以等待子进程结束后再继续往下运行,通常用于进程间的同步 p.join() print('Child process end.')
执行结果:
1 2 3 4
Parent process 62629. Child process will start Run child process test (62630). Child process end.
if __name__ == '__main__': print('Parent process %s.' % os.getpid()) #限制同时运行4个子进程 p = Pool(4) for i inrange(5): p.apply_async(long_time_task,args=(i,)) print('Waiting for all subprocesses done') #调用join()之前必须先调用close(),之后不能继续添加新的Process了 p.close() #等待所有子进程执行完毕 p.join() print('All subprocesses done.')
执行结果:
1 2 3 4 5 6 7 8 9 10 11 12 13
Parent process 63187. Waiting for all subprocesses done Run task 1 (63189)... Run task 2 (63190)... Run task 3 (63191)... Run task 0 (63188)... Task 3 runs 0.15 seconds. Run task 4 (63191)... Task 2 runs 0.96 seconds. Task 1 runs 1.18 seconds. Task 0 runs 1.72 seconds. Task 4 runs 2.17 seconds. All subprocesses done.