Python_队列Queue

队列(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()
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值