多进程,进程池。
1.多进程的调用
1.1 multiprocessing调用
1 from multiprocessing import Process 2 import time 3 def f(name): 4 time.sleep(1) 5 print('hello', name,time.ctime()) 6 7 if __name__ == '__main__': 8 p_list=[] 9 for i in range(3): 10 p = Process(target=f, args=('alvin',)) 11 p_list.append(p) 12 p.start() 13 for i in p_list: 14 i.join() 15 print('end')
运用for循环开启了3个子进程,全都join在主进程中。运行结果:
1 hello alvin Tue Oct 18 15:10:28 2016 2 hello alvin Tue Oct 18 15:10:28 2016 3 hello alvin Tue Oct 18 15:10:28 2016 4 end
结果显示:三个字符串同时打印出来。达到了多进程的目的。
1.2类来调用
1 from multiprocessing import Process 2 import time 3 4 class MyProcess(Process): 5 def __init__(self): 6 super(MyProcess, self).__init__() 7 # self.name = name 8 9 def run(self): 10 time.sleep(1) 11 print ('hello', self.name,time.ctime()) 12 13 14 if __name__ == '__main__': 15 p_list=[] 16 for i in range(3): 17 p = MyProcess() 18 p.start() 19 p_list.append(p) 20 21 for p in p_list: 22 p.join() 23 24 print('end')
同时开启了4个进程,但是并没有直接p.run()指令,但是结果显示:
1 hello MyProcess-1 Tue Oct 18 15:13:46 2016 2 hello MyProcess-2 Tue Oct 18 15:13:46 2016 3 hello MyProcess-3 Tue Oct 18 15:13:46 2016 4 end
可以看出:run函数是被自动执行的。self.name因为是被默认为进程的名称。
小总结:1.上述的四个进程在执行的过程中实现了真正的并发。但是在多过CPU个数的时候。。。
2.子进程的创建时将主进程完全copy一遍,很占资源的一种形式。
小细节:win系统中,创建子进程必须加main来标识主,子进程的不同。上述的例子中print(end)若是不在main中会产生影响。
2.进程之间的关系
1 from multiprocessing import Process 2 import os 3 import time 4 def info(title): 5 print(title) 6 print('module name:', __name__) 7 print('parent process:', os.getppid()) 8 print('process id:', os.getpid()) 9 10 11 def f(name): 12 info('\033[31;1mfunction f\033[0m') 13 print('hello', name) 14 15 if __name__ == '__main__': 16 info('\033[32;1mmain process line\033[0m') 17 time.sleep(5) 18 p = Process(target=info, args=('bob',)) 19 p.start() 20 p.join()
上述的代码中展示了进程的father进程的ID和自身的ID (通过os模块的getppid和getppid)
1 main process line 2 module name: __main__ 3 parent process: 11156 4 process id: 4592 5 bob 6 module name: __mp_main__ 7 parent process: 4592 8 process id: 7280
结果表明:主进程的名字为main,并且父进程为pycharm的pid。子进程的name不为main所以不会执行main中内容。
3.进程池
1 from multiprocessing import Process, Pool 2 import time 3 4 def Foo(i): 5 time.sleep(2) 6 return i + 100 7 8 9 def Bar(arg): 10 print('-->exec done:', arg) 11 12 if __name__ == '__main__': 13 14 pool = Pool(5) 15 16 for i in range(10): 17 pool.apply_async(func=Foo, args=(i,), callback=Bar) # 回调函数 每次运行完执行。bar的参数是foo的返回值。、 18 # pool.apply(func=Foo, args=(i,)) 19 pool.close() 21 pool.join()
22 print('end')
执行结果:没隔2秒钟出现5个执行结果
1 -->exec done: 100 2 -->exec done: 101 3 -->exec done: 102 4 -->exec done: 103 5 -->exec done: 104 6 -->exec done: 105 7 -->exec done: 106 8 -->exec done: 107 9 -->exec done: 108 10 -->exec done: 109 11 end