想要利用CPU多核资源一Python中多进程(一),


 大纲

使用多进程的原因

由于python中的多线程无法利用多核优势,如果想要利用CPU多核资源,需要使用多进程。

创建多进程

  1. Process([target [, args [, name [, kwargs]]]]) 
  2. # target 表示子进程要执行的任务 
  3. # args 元组参数 
  4. # kwargs 字典参数 
  5. # name 表示子进程的名称 

  1. # 方式一 
  2. import time 
  3. from multiprocessing import Process 
  4.  
  5. def run(name): 
  6.     print('{0} 开始跑步'.format(name)) 
  7.     time.sleep(2) 
  8.     print('{0} 跑步结束'.format(name)) 
  9.  
  10. p1 = Process(target=run, args=('小华', )) 
  11. p2 = Process(target=run, args=('小米', )) 
  12. p3 = Process(target=run, args=('小中', )) 
  13.  
  14. p1.start() 
  15. p2.start() 
  16. p3.start() 

 

方式一演示结果

  1. # 方式二 
  2. import time 
  3. from multiprocessing import Process 
  4.  
  5. class Run(Process): 
  6.     def __init__(self, name): 
  7.         Process.__init__(self) 
  8.         self.name = name 
  9.     def run(self): 
  10.         print('{0} 开始跑步'.format(name)) 
  11.         time.sleep(2) 
  12.         print('{0} 跑步结束'.format(name)) 
  13.  
  14. p1 = Run('小华') 
  15. p2 = Run('小米') 
  16. p3 = Run('小中') 
  17.  
  18. p1.start() 
  19. p2.start() 
  20. p3.start() 

 

方式二演示结果

守护进程

守护进程会在主进程代码执行结束后就终止。如果子进程的任务在主进程任务结束后就没有存在的必要了,那么该子进程应该在开启前就被设置成守护进程。主进程代码运行结束,守护进程随即终止。


启用time.sleep(3)和注释后两种结果演示

评论关闭