栈:先进后出(First In Last Out 简称 FILO)
队列: 先进先出(First In First Out 简称 FIFO)
from multiprocessing import Queue
q = Queue(num)
num : 队列的最大长度
q.get() # 阻塞等待获取数据,如果有数据直接获取,如果没有数据,阻塞等待
q.put() # 阻塞,如果可以继续往队列中放数据,就直接放,不能放就阻塞等待
q.get_nowait() # 不阻塞,如果有数据直接获取,没有数据就报错
q.put_nowait() # 不阻塞,如果可以继续往队列中放数据,就直接放,不能放就报错
from multiprocessing import Queue
q = Queue(3)
q.put(123)
q.put("aaa")
print(123)
q.put([1,2,3])
print(456)
q.put("你好")
print(789)
结果:
123
456
from multiprocessing import Queue
q = Queue(3)
q.put(123)
q.put("aaa")
print(123)
q.put([1,2,3])
print(456)
q.put_nowait("你好")
print(789)
报错:Full
from multiprocessing import Queue
q = Queue(3)
q.put(123)
q.put("aaa")
print(123)
q.put([1,2,3])
print(456)
try:
q.put_nowait("你好")
except:
print("队列满了")
print(789)
from multiprocessing import Queue
q = Queue(3)
q.put(123)
q.put("aaa")
q.put([1,2,3])
print(q.get())
print(q.get())
print(q.get())
print(q.get()) #阻塞等待
from multiprocessing import Queue
q = Queue(3)
q.put(123)
q.put("aaa")
q.put([1,2,3])
print(q.get())
print(q.get())
print(q.get())
print(q.get_nowait())
报错:Empty
生产者消费者模型
主要是为解耦
借助队列来实现生产者消费者模型
借助Queue解决生产者消费者模型
from multiprocessing import Process,Queue
def consumer(q,name):
while 1 :
info = q.get()
if info:
print("%s购买了%s" % (name,info))
else:
break
def producer(q,product):
for i in range(20):
info = product + "的拉菲%s箱" %str(i)
q.put(info)
q.put(None)
if __name__ == '__main__':
q = Queue(10)
p = Process(target=consumer,args=(q,"aa"))
p1 = Process(target=producer,args=(q,"97年的"))
p.start()
p1.start()
将生产者生产结束的标识,放到父进程中
from multiprocessing import Process, Queue
def consumer(q, name,color):
while 1:
info = q.get()
if info:
print("%s %s购买了%s 33[0m" % (color,name, info))
else:
break
def producer(q, product):
for i in range(20):
info = product + "的拉菲%s箱" % str(i)
q.put(info)
if __name__ == '__main__':
q = Queue(10)
p = Process(target=consumer, args=(q, "aa","