[TOC]
进程池Pool
当需要创建的子进程数量不多时,可以直接利用multiprocessing中的Process动态成生多个进程,但如果是上百甚至上千个目标,手动的去创建进程的工作量巨大,此时就可以用到multiprocessing模块提供的Pool方法。
初始化Pool时,可以指定一个最大进程数,当有新的请求提交到Pool中时,如果池还没有满,那么就会创建一个新的进程用来执行该请求;但如果池中的进程数已经达到指定的最大值,那么该请求就会等待,直到池中有进程结束,才会用之前的进程来执行新的任务,请看下面的实例:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
   |  from multiprocessing import Pool import os, time, random
  def worker(msg):     t_start = time.time()     print("%s开始执行,进程号为%d" % (msg,os.getpid()))          time.sleep(random.random()*2)      t_stop = time.time()     print(msg,"执行完毕,耗时%0.2f" % (t_stop-t_start))
  po = Pool(3)   for i in range(0,10):               po.apply_async(worker,(i,))
  print("----start----") po.close()   po.join()   print("-----end-----")
 
  | 
 
----start----
——start——
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
   | 0开始执行,进程号为21466 1开始执行,进程号为21468 2开始执行,进程号为21467 0 执行完毕,耗时1.01 3开始执行,进程号为21466 2 执行完毕,耗时1.24 4开始执行,进程号为21467 3 执行完毕,耗时0.56 5开始执行,进程号为21466 1 执行完毕,耗时1.68 6开始执行,进程号为21468 4 执行完毕,耗时0.67 7开始执行,进程号为21467 5 执行完毕,耗时0.83 8开始执行,进程号为21466 6 执行完毕,耗时0.75 9开始执行,进程号为21468 7 执行完毕,耗时1.03 8 执行完毕,耗时1.05 9 执行完毕,耗时1.69 -----end-----
   | 
 
multiprocessing.Pool常用函数解析:
apply_async(func[, args[, kwds]]) :使用非阻塞方式调用func(并行执行,堵塞方式必须等待上一个进程退出才能执行下一个进程),args为传递给func的参数列表,kwds为传递给func的关键字参数列表;
close():关闭Pool,使其不再接受新的任务;
terminate():不管任务是否完成,立即终止;
join():主进程阻塞,等待子进程的退出, 必须在close或terminate之后使用;
进程池中的Queue
如果要使用Pool创建进程,就需要使用multiprocessing.Manager()中的Queue(),而不是multiprocessing.Queue(),否则会得到一条如下的错误信息:
RuntimeError: Queue objects should only be shared between processes through inheritance.
下面的实例演示了进程池中的进程如何通信:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
   | 
 
  from multiprocessing import Manager,Pool import os,time,random
  def reader(q):     print("reader启动(%s),父进程为(%s)" % (os.getpid(), os.getppid()))     for i in range(q.qsize()):         print("reader从Queue获取到消息:%s" % q.get(True))
  def writer(q):     print("writer启动(%s),父进程为(%s)" % (os.getpid(), os.getppid()))     for i in "itcast":         q.put(i)
  if __name__=="__main__":     print("(%s) start" % os.getpid())     q = Manager().Queue()       po = Pool()     po.apply_async(writer, (q,))
      time.sleep(1)  
      po.apply_async(reader, (q,))     po.close()     po.join()     print("(%s) End" % os.getpid())
 
  | 
 
运行结果:
1 2 3 4 5 6 7 8 9 10
   | (11095) start writer启动(11097),父进程为(11095) reader启动(11098),父进程为(11095) reader从Queue获取到消息:i reader从Queue获取到消息:t reader从Queue获取到消息:c reader从Queue获取到消息:a reader从Queue获取到消息:s reader从Queue获取到消息:t (11095) End
   | 
 
应用:文件夹copy器(多进程版)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68
   | import multiprocessing import os import time import random
 
  def copy_file(queue, file_name,source_folder_name,  dest_folder_name):     """copy文件到指定的路径"""     f_read = open(source_folder_name + "/" + file_name, "rb")     f_write = open(dest_folder_name + "/" + file_name, "wb")     while True:         time.sleep(random.random())         content = f_read.read(1024)         if content:             f_write.write(content)         else:             break     f_read.close()     f_write.close()
           queue.put(file_name)
 
  def main():          source_folder_name = input("请输入要复制文件夹名字:")
           dest_folder_name = source_folder_name + "[副本]"
           try:         os.mkdir(dest_folder_name)     except:         pass  
           file_names = os.listdir(source_folder_name)
           queue = multiprocessing.Manager().Queue()
           pool = multiprocessing.Pool(3)
      for file_name in file_names:                  pool.apply_async(copy_file, args=(queue, file_name, source_folder_name, dest_folder_name))
           pool.close()
      all_file_num = len(file_names)     while True:         file_name = queue.get()         if file_name in file_names:             file_names.remove(file_name)
          copy_rate = (all_file_num-len(file_names))*100/all_file_num         print("\r%.2f...(%s)" % (copy_rate, file_name) + " "*50, end="")         if copy_rate >= 100:             break     print()
 
  if __name__ == "__main__":     main()
   |