Python队列queue模块

 

Python中queue模块常用来处理队列相关问题

队列常用于生产者消费者模型,主要功能为提高效率和程序解耦

1. queue模块的基本使用和相关说明

# -*- coding:utf-8 -*-
# Author:Wong Du

'''
队列常用于生产者消费者模型,
主要功能为提高效率和程序解耦
'''

import queue
"""实例化队列对象不同规则的三种方法"""
q1 = queue.Queue(maxsize=2)   # 先入先出
q2 = queue.LifoQueue(maxsize=3)     # 后入先出,Last in first out
q3 = queue.PriorityQueue(maxsize=5) # 根据存储数据的优先级决定谁先出队列

"""
添加数据进队列中,可添加str、list、tuple等
当添加的数据量超过队列上限的时候,程序会卡住,直到有人从队列中取出数据
若想让程序不卡住,可以用put_nowait添加数据和配置block或timeout的put参数
来让程序抛出异常,从而进行异常处理或其他操作
"""
q1.put("caiyun")
q1.put( [1, 2, 3, 4, 5] )
# q1.put_nowait(2)
# q1.put(2, block=False)
# q1.put(2, timeout=3)
q2.put("caiyun")
q2.put( (1, 2, 3, 4, 5) )
q3.put(("Wong", 123))
q3.put(("Caiyun", 322))
q3.put(("dudu", 98))

"""
获取队列中的数据,同理
当队列中没有数据的时候,程序会卡住,直到有人添加数据在队列中
若想让程序不卡住,可以用get_nowait添加数据和配置block或timeout的put参数
来让程序抛出异常,从而进行异常处理或其他操作
"""
print("\033[32;1mQueue Info\033[0m".center(35,'-'))
print(q1.get())
print(q1.get())
# q1.get_nowait()
# q1.get(block=False)
# q1.get(timeout=3)
print("\033[33;1mLifoQueue Info\033[0m".center(35,'-'))
print(q2.get())
print(q2.get())
print("\033[34;1mPriorityQueue Info\033[0m".center(35,'-'))
print(q3.get()[0])
print(q3.get())
# print(q3.get())

"""队列判断和计数,判断是否为空,是否已满,队列长度计数"""
print(q1.empty())
print(q1.full())
print(q3.qsize())

2. queue模块的简单应用

 1 # -*- coding:utf-8 -*-
 2 # Author:Wong Du
 3 
 4 import time
 5 import queue
 6 import threading
 7 
 8 q = queue.Queue(maxsize=10)
 9 
10 def producer(pname):
11     count = 1
12     while True:
13         q.put("baozi%s" % count)
14         print("\033[31;1m[%s] 生产了 [baozi%s]...\033[0m" %(pname, count))
15         count += 1
16         time.sleep(0.5)
17 
18 def consumer(cname):
19     while True:
20         print("\033[33;1m[%s] 收到了 [%s],并把它吃了...\033[0m" %(cname, q.get()))
21         time.sleep(2)
22 
23 p1 = threading.Thread(target=producer, args=("Caiyun", ))
24 p1.start()
25 
26 c1 = threading.Thread(target=consumer, args=("dudu", ))
27 c2 = threading.Thread(target=consumer, args=("wong", ))
28 c1.start()
29 # c2.start()
queue&threading_生产者消费者实例

猜你喜欢

转载自www.cnblogs.com/Caiyundo/p/9487857.html