队列(queque)
主要作用:解耦,是程序实现松耦合,提高处理效率
queque is especially useful in thread programming when information must be exchanged
safety between multiple threads.
Class queue.Queue(maxsize=0) # if one is login firstly, it will be logout firstly(FIFO)
Class queue.LifoQueue(maxsize=0) # if one is login lastly, it will be logout firstly(LIFO)
Class queue.PriorityQueue(maxsize=0) # You can set the priority of the member of queue
Constructor for a priority queue. maxsize is an integer that sets the upperbound limit on the
number of items that can be placed in the queue. Insertion will block once this size has been
reached, until queue items are consumed. If maxsize is less than or equal to zero, the queue
size is infinite.
The lowest valued entries are retrieved first (The lowest valued entry is the one returned by
sorted(list(entries)[0]). A typical pattern for entries is a tuple in the form:(priority_number, data).
exception queue.Empty
Exception raised when non-blocking get()(or get no_wait()) is called on a queue object which is empty.
下面的例子展示了队列的用法:
# Author : Xuefeng
import queue
# 先入先出队列
# q = queue.Queue(maxsize=3) # Set the size of queue
# 先入后出队列
# q = queue.LifoQueue()
# 设置优先级队列
q = queue.PriorityQueue()
# 向队列里添加元素
# q.put("d1")
# q.put("d2")
# q.put("d3")
# Set the priority
q.put((1, "Jim", 2))
q.put((15, "Tom", 10))
q.put((9, "Mary", 5))
# 打印队列大小
print(q.qsize())
# 获取队列
print(q.get_nowait())
print(q.get())
print(q.get())
# print(q.get())
# print(q.get(block=False)) # If no data come,it will not to wait.
# print(q.get(timeout=4)) # wait for 4 second, if no data coming, show error
利用队列创建生产者消费者模型:
# Author : Xuefeng
import threading
import queue
import time
q = queue.Queue(maxsize=10)
def producer(name):
'''
定义生产者,生产骨头
:param name: 生产者的名字
:return:
'''
count = 1
while True:
# 循环将骨头放入队列
q.put("Bone %d" %count)
count += 1
print("Produce %d th bone\n" %count)
time.sleep(0.1)
# print("Wait for all bone be fetched...")
# q.join()
# print("All bones are fetched...")
def consumer(n):
'''
定义消费者,取骨头
:param n: 消费者的名字
:return:
'''
while True:
# 判断队列中有没有骨头对象
if q.qsize() > 0:
print("%s Fetched" %n, q.get(), "\n")
q.task_done() # tell that this task have been done
time.sleep(2)
p = threading.Thread(target=producer, args=("Jim", ))
c = threading.Thread(target=consumer, args=("Tom", ))
c1 = threading.Thread(target=consumer, args=("Mary", ))
p.start()
c.start()
c1.start()
2847

被折叠的 条评论
为什么被折叠?



