队列:管道或者巷子,先进先出
队列基本操作
import queue
#q=queue.Queue(3) # 默认是先进先出(FIFO)
# q.put(111)
# q.put("hello")
# q.put(222)
# q.put(223,False)
#
# print(q.get())
# # print(q.get())
# # print(q.get())
# #
# q.get(False)
# queue 优点: 线程安全的
# join和task_done
# q=queue.Queue(5)
#
# q.put(111)
# q.put(222)
# q.put(22222)
#
#
# while not q.empty():
# a=q.get()
# print(a)
# q.task_done()
#
#
# b=q.get()
# print(b)
# q.task_done()
#
# q.join()
#
# print("ending")
# 先进后出模式
# q=queue.LifoQueue() # Lifo last in first out
#
#
# q.put(111)
# q.put(222)
# q.put(333)
#
# print(q.get())
# print(q.get())
# print(q.get())
# 优先级
#
# q=queue.PriorityQueue()
#
# q.put([4,"hello4"])
# q.put([1,"hello"])
# q.put([2,"hello2"])
#
# print(q.get())
# print(q.get())
# import queue
#
#
# q=queue.Queue()
#
# q.put(111)
# q.put(2222)
# q.put(22333)
#
# print( )
队列的生产者消费者模型
#生产者消费者模型
import time,random
import queue,threading
q = queue.Queue(5)
def Producer(name):
count = 0
while count <10:
print("making........")
time.sleep(2)
q.put(count)
print('Producer %s has produced %s baozi..' %(name, count))
count +=1
#q.task_done()
#q.join()
print("ok......")
def Consumer(name):
count = 0
while count <10:
time.sleep(1)
if not q.empty():
data = q.get()
#q.task_done()
#q.join()
print(data)
print('\033[32;1mConsumer %s has eat %s baozi...\033[0m' %(name, data))
else:
print("-----no baozi anymore----")
count +=1
p1 = threading.Thread(target=Producer, args=('A',))
c1 = threading.Thread(target=Consumer, args=('B',))
# c2 = threading.Thread(target=Consumer, args=('C',))
# c3 = threading.Thread(target=Consumer, args=('D',))
p1.start()
c1.start()
# c2.start()
# c3.start()