进程间通信与进程池
进程间通信-Queue
通常利用multiprocessing模块的Queue实现多线程之间的数据传递,Queue本身是一个消息列队程序
- q=Queue()#若括号中没有指定最大可接受的消息数量或数量为负值,那么代表可接受的消息数量没有上限直到内存耗尽
- Queue.qsize():返回当前队列包含的消息数量
- Queue.empty():队列为空返回True
- Queue.full():队列为满返回True
- Queue.get([block[,timeout]]):获取队列中的一条消息,然后将其从队列中移除,block默认值为True
- 若block使用默认值,且没有设置timeout(单位秒),消息队列如果为空,此时程序将被阻塞(停在读取状态),直到从消息队列读到消息为止,如果设置了timeout,则会等待timeout秒。若还没有读到任何消息,抛出Queue.Empty异常
- 若block值为False,消息队列如果为空,则会理科抛出“Queue.Empty”异常
- Queue.get_nowait():相当Queue.get(False);
- Queue.put(item,[block[, timeout]]):将item消息写入队列,block默认值为True;
实例
from multiprocessing import Process,Queue
import os,time,random
def write(q):
for value in ['A','B','C']:
print('Put %s to queue ... '%value)
q.put(value)
time.sleep(random.random())
def read(q):
while True:
if not q.empty():
value = q.get(True)
print('Get %s from queue.' %value)
time.sleep(random.random())
else:
break
if __name__=='__main__':
q = Queue()
pw = Process(target=write,args=(q,))
pr = Process(target=read,args=(q,))
pw.start()
pw.join()
pr.join()
pr.join()
print('')
print('所有数据都写入并且已经读完')
网友评论