(二)使用Pool类创造多进程及进程间通信
一、Intro
1、multiprocessing的Pool可以提供指定数量的进程供用户使用,当一个新的请求提交到pool时,若pool还没有满,则会创建一个新的进程,直到pool中的进程数达到最大。若进程池进程数已达上限,则任务将会等待,直到池中有进程结束。
2、multiprocessing的Pipe类用于两个进程之间的通信,而Queue类实现多个进程之间的通信。
3、Queue基于“队列”的数据结构进行操作,分为Put方法和Get方法。
(1)Put用于插入元素,参数为blocked(True/False,False时在队列满时直接提示Queue.Full异常)和timeout(若队列已满,任务入队将暂缓timeout时间,届时若队列依然没有空余空间,则Queue.Full异常)
(2)Get用于取出元素,同理参数为blocked和timeout。若无元素可取,则返回Queue.Empty异常。
二、pool类创造进程
from multiprocessing import Pool import os,time,random def run_task(name): print 'Task %s (pid=%s) is running...' % (name,os.getpid()) time.sleep(random.random()*3) print 'Task %s end.' % name if __name__=='__main__': print 'Current process %s' % os.getpid() p=Pool(processes=3) for i in range(5): p.apply_async(run_task,args=(i,)) print 'Wait for a second' p.close() p.join() print 'Done'
Current process 3696 Wait for a second Task 0 (pid= 364) is running... Task 1 (pid= 4828) is running... Task 2 (pid= 5888) is running... Task 2 end. Task 3 (pid= 5888) is running... Task 0 end. Task 4 (pid= 364) is running... Task 4 end. Task 3 end. Task 1 end. Done Process finished with exit code 0
三、进程间通信
from multiprocessing import Process,Queue
import os,time,random
def proc_write(q,urls):
print 'Process (%s) is writing' % os.getpid()
for url in urls:
q.put(url)
print 'Insert %s to queue...' % url
time.sleep(random.random())
def proc_read(q):
print 'Process (%s) is reading...' % os.getpid()
while True:
url=q.get()
print 'Read %s and remove' % url
if __name__=='__main__':
q=Queue()
p_w1=Process(target=proc_write,args=(q,[1,"bob",23]))
p_w2=Process(target=proc_write,args=(q,["www.baidu.com",34,222]))
p_r=Process(target=proc_read,args=(q,))
p_w1.start()
p_w2.start()
p_r.start()
p_w1.join()
p_w2.join()
p_r.terminate()
Process (3700) is writing Insert 1 to queue... Process (5184) is writing Insert www.baidu.com to queue... Process (1900) is reading... Read 1 and remove Read www.baidu.com and remove Insert bob to queue... Read bob and remove Insert 34 to queue... Read 34 and remove Insert 23 to queue... Read 23 and remove Insert 222 to queue... Read 222 and remove Process finished with exit code 0
通过分配p_w1,p_w2和p_r三个子进程,使它们独立于当前的父进程分别调用proc_write和proc_read,实现并行(不用按照主程序逻辑行的顺序依次运行)。
坐飞机咯。等回来更新运行结果~

浙公网安备 33010602011771号