python学习 多进程Process/进程池Pool/队列Queue

  1 #进程Process
  2 from multiprocessing import Process
  3 from time import sleep
  4 
  5 def xx(name):
  6     for i in range(3):
  7         print('test.{}'.format(name))
  8         sleep(1)
  9 
 10 if __name__ == '__main__':
 11     a=Process(target=xx,args=('alex',))  #----子进程做事情,主进程也可以干活
 12     a.start()#创建子进程
 13     # a.join()#等待子进程全部结束,才继续下一步执行
 14     a.join(timeout=1)#timeout为等待时间
 15     a.terminate()#强制结束
 16     print('main')
 17 
 18 
 19 #Process子类创建子进程
 20 class myProcess(Process):
 21     def __init__(self,name):
 22         Process.__init__(self)
 23         self.name=name
 24 
 25     #重写了Process类的run()方法
 26     def run(self):
 27         print('xxxx-{}'.format(self.name))
 28 
 29 if __name__ == '__main__':
 30     a=myProcess('joe')
 31     a.start()
 32 
 33 
 34 #进程池Pool---主进程一般用来等待,真正的任务都在子进程进行
 35 from multiprocessing import Pool
 36 import os
 37 
 38 def A(name):
 39     for i in range(5):
 40         print('i-{},name-{},os-{}'.format(i,name,os.getpid()))
 41         sleep(1)
 42 
 43 if __name__ == '__main__':
 44     po = Pool(3) #进程池中对有3个进程一起执行
 45     for a in range(10):
 46         print(a)
 47         po.apply_async(A,(a,))  #非堵塞模式,即一起执行
 48         # po.apply(A,(a,))   #堵塞模式,即依次排队执行。(该方法几乎不用)
 49 
 50     po.close() #关闭进程池
 51     po.join()
 52 
 53 
 54 #Queue-队列(先进先出),可以作用于进程之间的通讯。
 55 from multiprocessing import Queue
 56 '''
 57 q=Queue(3) #创建一个消息队列,有三个
 58 q=Queue()  #创建一个队列,可有无数个值
 59 q.put('hh1') #往队列存一个值
 60 print(q.qsize()) #统计队列有多少值
 61 print(q.get())  #从队列取一个值
 62 print(q.empty())  #判断队列是否为空
 63 print(q.full())  #判断队列是否是man的
 64 print(q.get_nowait()) #不等待,立即取。队列为空的时候会报错
 65 print(q.put_nowait('hh2')) #不等待,立即存。队列满了的时候会报错
 66 '''
 67 #例子-Process进程之间的通讯
 68 from multiprocessing import Process,Queue
 69 from time import sleep
 70 
 71 def write(q):
 72     for value in ['a','b','c']:
 73         print('put {} in queue'.format(value))
 74         q.put(value)
 75         sleep(1)
 76 
 77 def read(q):
 78     while True:
 79         if not q.empty():
 80             value1=q.get()
 81             print('get {} in queue'.format(value1))
 82             sleep(1)
 83         else:
 84             break
 85 
 86 if __name__ == '__main__':
 87     q=Queue()
 88     #方式一----按顺序执行
 89     pw=Process(target=write,args=(q,))
 90     pw.start()
 91     pw.join()
 92     pr = Process(target=read, args=(q,))
 93     pr.start()
 94     pr.join()
 95 
 96     # #方式二----同时执行
 97     # pw=Process(target=write,args=(q,))
 98     # pr = Process(target=read, args=(q,))
 99     # pw.start()
100     # pr.start()
101     # pw.join()
102     # pr.join()
103 
104 
105 #例子-进程池内各进程之间的通讯
106 from multiprocessing import Manager,Queue,Pool
107 from time import sleep
108 
109 def writer(q):
110     for i in 'alex':
111         print(i)
112         q.put(i)
113         sleep(1)
114 
115 def reader(q):
116     #方式一:
117     for i in range(q.qsize()):
118         print(i)
119         print(q.qsize())
120         a=q.get()
121         print('get {} in queue'.format(a))
122         sleep(1)
123     # #方式二:
124     # while True:
125     #     if not q.empty():
126     #         value1=q.get()
127     #         print('get {} in queue'.format(value1))
128     #         sleep(1)
129     #     else:
130     #         break
131 
132 if __name__ == '__main__':
133     q=Manager().Queue()
134     po=Pool()
135     #方式一调用---使用阻塞模式创建进程,这样就不需要在reader中使用死循环了,可以让writer完全执行完之后,再用reader
136     # po.apply(writer,(q,))
137     # po.apply(reader,(q,))
138     #方式二调用---使用非阻塞模式创建进程,可以writer一次同时reader一次,writer和reader一起执行
139     po.apply_async(writer,(q,))
140     po.apply_async(reader,(q,))
141     po.close()
142     po.join()
143 
144 
145 #例子---拷贝多个文件
146 from multiprocessing import Manager,Pool,Queue
147 import os
148 
149 def copyFileTask(name,old_filename,new_filename,qu):
150     with open(old_filename+'/'+name,'r') as f1:
151         content=f1.read()
152         with open(new_filename+'/'+name,'w') as f2:
153             f2.write(content)
154             qu.put(content)
155 
156 def main():
157     #1、找到要复制的文件夹名字
158     old_filename=r'C:\Users\ASUS\Desktop\test'
159     #2、创建新文件夹
160     new_filename=old_filename+'复件'
161     print(new_filename)
162     os.mkdir(new_filename)
163     #3、获取要复制的文件夹下所有的文件名称
164     filenames=os.listdir(old_filename)
165     #4、使用多进程,将旧文件内容拷贝到新文件里
166     ####方法一:使用线程池多进程####
167     # po=Pool(3)
168     # qu=Manager().Queue()
169     # for name in filenames:
170     #     po.apply_async(copyFileTask,(name,old_filename,new_filename,qu))
171 
172     ####方法二:使用多进程####
173     qu=Queue()
174     for name in filenames:
175         a=Process(target=copyFileTask,args=(name,old_filename,new_filename,qu))
176         a.start()
177         # a.join()
178 
179     num=0
180     allNum=len(filenames)
181     while True:
182         qu.get()
183         num=num+1
184         Rate=num/allNum
185         # \r 默认表示将输出的内容返回到第一个指针,这样的话,后面的内容会覆盖前面的内容
186         print('\rcopy的进度是:%.2f%%'%(Rate*100),end="")
187         if num==allNum:
188             break
189 
190     # po.close()
191     # po.join()
192 
193 if __name__ == '__main__':
194     main()

 

posted on 2019-08-18 15:10  cherry_ning  阅读(645)  评论(0)    收藏  举报

导航