1.1 Queue有两个方法:
-
Put方法:以插入数据到队列中,他还有两个可选参数:blocked和timeout。详情自行百度
-
Get方法:从队列读取并且删除一个元素。同样,他还有两个可选参数:blocked和timeout。详情自行百度
#!coding:utf-8 from multiprocessing import Process, Queue import os,time,random #写数据进程执行的代码 def proc_write(q,urls): print 'Process is write....' for url in urls:
q.put(url) print 'put %s to queue... ' %url
time.sleep(random.random()) #读数据进程的代码 def proc_read(q): print('Process is reading...') while True:
url = q.get(True)
print('Get %s from queue' %url) if __name__ == '__main__': #父进程创建Queue,并传给各个子进程 q = Queue()
proc_write1 = Process(target=proc_write,args=(q,['url_1','url_2','url_3']))
proc_write2 = Process(target=proc_write,args=(q,['url_4','url_5','url_6']))
proc_reader = Process(target=proc_read,args=(q,)) #启动子进程,写入 proc_write1.start()
proc_write2.start()
proc_reader.start() #等待proc_write1结束 proc_write1.join()
proc_write2.join() #proc_raader进程是死循环,强制结束 proc_reader.terminate()
-
运行截图:
1.2 Pipe通信机制,
* Pipe常用于两个进程,两个进程分别位于管道的两端
* Pipe方法返回(conn1,conn2)代表一个管道的两个端,Pipe方法有duplex参数,默认为True,即全双工模式,若为FALSE,conn1只负责接收信息,conn2负责发送,
* send和recv方法分别为发送和接收信息。
#!coding:utf-8 import multiprocessing import os,time,random #写数据进程执行的代码 def proc_send(pipe,urls): #print 'Process is write....' for url in urls: print 'Process is send :%s' %url
pipe.send(url)
time.sleep(random.random()) #读数据进程的代码 def proc_recv(pipe): while True:
print('Process rev:%s' %pipe.recv())
time.sleep(random.random()) if __name__ == '__main__': #父进程创建pipe,并传给各个子进程 pipe = multiprocessing.Pipe()
p1 = multiprocessing.Process(target=proc_send,args=(pipe[0],['url_'+str(i) for i in range(10) ]))
p2 = multiprocessing.Process(target=proc_recv,args=(pipe[1],)) #启动子进程,写入 p1.start()
p2.start()
p1.join()
p2.terminate()
-
运行结果;