#queue队列 #生产者消费者模型 #queue队列 #有顺序的容器
#程序解耦
#提高运行效率 #class queue.Queue(maxsize=0) #先入先出
#class queue.LifoQueue(maxsize=0)最后在第一
#class queue.PriorityQueue(maxsize=0) #存储数据时可设置优先级的队列#VIP客户 #Queue.qsize()
#Queue.empty() #return True if empty
#Queue.full() # return True if full
#Queue.put(item, block=True, timeout=None) '''
import queue
q = queue.Queue()
q.put('d1')
q.put('d2')
q.put('d3')
print (q.qsize()) print(q.get())
print(q.get())
print(q.get())
print(q.get())#没有东西就卡死了
'''
'''
import queue q = queue.Queue()
q.put(1)
q.put(2)
q.put(3) print(q.get())
print(q.get())
print(q.get())
#print(q.get())#没有东西就卡死了 print(q.qsize())#查看
q.get_nowait()#异常
'''
'''
#后进先出
import queue
q = queue.LifoQueue()
q.put(1)
q.put(2)
q.put(3) print(q.get())
print(q.get())
print(q.get())
'''
'''
#VIP
import queue q = queue.PriorityQueue()
q.put((-1,'c'))
q.put((3,'h'))
q.put((10,'alex'))
q.put((6,'w')) print(q.get())
print(q.get())
print(q.get())
print(q.get())
'''
#生产者消费者模型 import threading,time
import queue q = queue.Queue(maxsize=10) def Producer(name):
count =1
while True:
q.put('骨头%s'% count)
print ('生成了骨头',count)
count +=1
time.sleep(0.1)
def Consumer(name):
#while q.qsize() > 0 :
while True:
print ('[%s] 取到 [%s] 并且吃了它...'% (name,q.get()))
time.sleep(1) p = threading.Thread(target=Producer,args=('Alex',))
c = threading.Thread(target=Consumer,args=('陈荣华',))
c1 = threading.Thread(target=Consumer,args=('王森',))
p.start()
c.start()
c1.start() #下面来学习一个最基本的生产者消费者模型的例子
'''
import threading
import queue def producer():
for i in range(10):
q.put("骨头 %s" % i ) print("开始等待所有的骨头被取走...")
q.join()
print("所有的骨头被取完了...") def consumer(n):
while q.qsize() >0:
print("%s 取到" %n , q.get())
q.task_done() #告知这个任务执行完了 q = queue.Queue()
p = threading.Thread(target=producer,)
p.start()
c1 = consumer("李闯")
''' '''
import time,random
import queue,threading
q = queue.Queue()
def Producer(name):
count = 0
while count <20:
time.sleep(random.randrange(3))
q.put(count)
print('Producer %s has produced %s baozi..' %(name, count))
count +=1
def Consumer(name):
count = 0
while count <20:
time.sleep(random.randrange(4))
if not q.empty():
data = q.get()
print(data)
print('1mConsumer %s has eat %s baozi...' %(name, data))
else:
print("-----no baozi anymore----")
count +=1
p1 = threading.Thread(target=Producer, args=('A',))
c1 = threading.Thread(target=Consumer, args=('B',))
p1.start()
c1.start()
'''
#queue队列 #生产者消费者模型