import os 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))
Process (876) start... I (876) just created a child process (877). I am child process (877) and my parent is 876.
from multiprocessing import Process import os # 子进程要执行的代码 def run_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() p.join() print(‘Child process end.‘)
Parent process 928.
Child process will start.
Run child process test (929)...
Process end.
创建子进程时,只需要传入一个执行函数和函数的参数,创建一个Process
实例,用start()
方法启动,这样创建进程比fork()
还要简单。
join()
方法可以等待子进程结束后再继续往下运行,通常用于进程间的同步。
Pool
from multiprocessing import Pool import os, time, random def long_time_task(name): print(‘Run task %s (%s)...‘ % (name, os.getpid())) start = time.time() time.sleep(random.random() * 3) end = time.time() print(‘Task %s runs %0.2f seconds.‘ % (name, (end - start))) if __name__==‘__main__‘: print(‘Parent process %s.‘ % os.getpid()) p = Pool(4) 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.‘)
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.