1.队列
from multiprocessing import Queue q = Queue(5) #创建队列对象,队列大小为5,队列中只能存放5个元素 q.put(1) #往队列中添加元素 q.put(2) q.put(3) q.put(4) q.put(5) print(q.full()) #检测队列是否满了~ print(q.get()) #取出队列中的值 print(q.get()) print(q.get()) print(q.get()) print(q.get()) print(q.empty()) #检测队列为空
结果: 如果队列中的值满了,继续用put()方法往队列中添加元素,则会阻塞,
如果队列为空,继续用get()方法取队列中的元素,同样也会阻塞。
get_nowait()方法:
返回q中的一个项,如果q为空此方法则阻塞,知道队列中有项目可以用为止。用于控制阻塞行为,默认为True,如果设置为False,将引发Queue.Empty异常。
from multiprocessing import Queue q = Queue(5) #创建队列对象,队列大小为5,队列中只能存放5个元素 q.put(1) #往队列中添加元素 q.put(2) q.put(3) q.put(4) q.put(5) print(q.full()) #检测队列是否满了~ print(q.get()) #取出队列中的值 print(q.get()) print(q.get()) print(q.get()) print(q.get()) print(q.empty()) #检测队列为空 q.get_nowait() #返回q中的一个项,如果q为空此方法则阻塞,知道队列中有项目可以用为止。 # 用于控制阻塞行为,默认为True,如果设置为False,将引发Queue.Empty异常。
结果:
用while循环和异常处理实现即使队列中没有元素,也不阻塞,而是等待队列中有了元素之后,再获取元素。
from multiprocessing import Queue import time q = Queue(5) #创建队列对象,队列大小为5,队列中只能存放5个元素 q.put(1) #往队列中添加元素 q.put(2) q.put(3) q.put(4) q.put(5) print(q.full()) #检测队列是否满了~ print(q.get()) #取出队列中的值 print(q.get()) print(q.get()) print(q.get()) print(q.get()) print(q.empty()) #检测队列为空 while True: try: q.get_nowait() #返回q中的一个项,如果q为空此方法则阻塞,知道队列中有项目可以用为止。 # 用于控制阻塞行为,默认为True,如果设置为False,将引发Queue.Empty异常。 except: print(‘队列已空!‘) #用异常处理解决异常 time.sleep(1) #等1秒之后,再获取队列中的元素
结果:
通过队列在两个子进程之间通信。
from multiprocessing import Queue,Process class MyClass(Process): def __init__(self,q): super().__init__() self.q = q def run(self): self.q.put(‘hello‘) #将数据添加到队列中 class Consume(Process): def __init__(self,q): super().__init__() self.q = q def run(self): print(self.q.get()) #将数据从队列中取出 if __name__ == ‘__main__‘: q = Queue() p = MyClass(q) #生产数据子进程 p.start() c = Consume(q) #消耗数据子进程 c.start()
结果:
原文:https://www.cnblogs.com/wangdianchao/p/12070825.html