print('Process (%s) start...' % os.getpid()) pid = os.fork() if pid == 0: print('i am 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 (2291) start... I (2291) just created a child process (2294). i am process (2294) and my parent is2291.
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() p.join() print('Child process end')
结果如下:
1 2 3 4
Parent process 2357. Child process will start. Run child process test (2360)... Child process end
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...') # 调用close后就不能添加新的Process了 p.close() # Pool对象调用join方法会等待所有进程执行完毕 p.join() print('All subprocesses done.')
子进程
subprocess模块可以非常方便地启动一个子进程,然后控制其输入和输出。
1 2 3 4 5 6 7 8 9 10 11 12 13
import subprocess
print('$ nslookup www.python.org') r = subprocess.call(['nslookup','www.python.org']) print('Exit code:',r)
# 以Queue为例 from multiprocessing import Process, Queue import os, time, random
# 写数据进程执行的代码: defwrite(q): print('Process to write: %s' % os.getpid()) for value in ['A', 'B', 'C']: print('Put %s to queue...' % value) q.put(value) time.sleep(random.random())
# 读数据进程执行的代码: defread(q): print('Process to read: %s' % os.getpid()) whileTrue: value = q.get(True) print('Get %s from eue.' % value)