python queue

The Queue module has been renamed to queue in Python 3. The 2to3 tool will automatically adapt imports when converting your sources to Python 3.

Source code: Lib/Queue.py


The Queue module implements multi-producer, multi-consumer queues. It is especially useful in threaded programming when information must be exchanged safely between multiple threads. The Queue class in this module implements all the required locking semantics. It depends on the availability of thread support in Python; see the threading module.

The module implements three types of queue, which differ only in the order in which the entries are retrieved. In a FIFO queue, the first tasks added are the first retrieved. In a LIFO queue, the most recently added entry is the first retrieved (operating like a stack). With a priority queue, the entries are kept sorted (using the heapq module) and the lowest valued entry is retrieved first.

The Queue module defines the following classes and exceptions:

class  Queue. Queue ( maxsize=0 )

Constructor for a FIFO 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.

class  Queue. LifoQueue ( maxsize=0 )

Constructor for a LIFO 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.

New in version 2.6.

class  Queue. PriorityQueue ( maxsize=0 )

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).

New in version 2.6.

exception  Queue. Empty

Exception raised when non-blocking get() (or get_nowait()) is called on a Queue object which is empty.

exception  Queue. Full

Exception raised when non-blocking put() (or put_nowait()) is called on a Queue object which is full.

See also

 

collections.deque is an alternative implementation of unbounded queues with fast atomic append() and popleft()operations that do not require locking.

8.10.1. Queue Objects

Queue objects (QueueLifoQueue, or PriorityQueue) provide the public methods described below.

Queue. qsize ( )

Return the approximate size of the queue. Note, qsize() > 0 doesn’t guarantee that a subsequent get() will not block, nor will qsize() < maxsize guarantee that put() will not block.

Queue. empty ( )

Return True if the queue is empty, False otherwise. If empty() returns True it doesn’t guarantee that a subsequent call to put() will not block. Similarly, if empty() returns False it doesn’t guarantee that a subsequent call to get() will not block.

Queue. full ( )

Return True if the queue is full, False otherwise. If full() returns True it doesn’t guarantee that a subsequent call to get() will not block. Similarly, if full() returns False it doesn’t guarantee that a subsequent call to put() will not block.

Queue. put ( item [block [timeout ] ] )

Put item into the queue. If optional args block is true and timeout is None (the default), block if necessary until a free slot is available. If timeout is a positive number, it blocks at most timeout seconds and raises the Full exception if no free slot was available within that time. Otherwise (block is false), put an item on the queue if a free slot is immediately available, else raise the Full exception (timeout is ignored in that case).

New in version 2.3: The timeout parameter.

Queue. put_nowait ( item )

Equivalent to put(item, False).

Queue. get ( [ block [timeout ] ] )

Remove and return an item from the queue. If optional args block is true and timeout is None (the default), block if necessary until an item is available. If timeout is a positive number, it blocks at most timeout seconds and raises the Empty exception if no item was available within that time. Otherwise (block is false), return an item if one is immediately available, else raise the Empty exception (timeout is ignored in that case).

New in version 2.3: The timeout parameter.

Queue. get_nowait ( )

Equivalent to get(False).

Two methods are offered to support tracking whether enqueued tasks have been fully processed by daemon consumer threads.

Queue. task_done ( )

Indicate that a formerly enqueued task is complete. Used by queue consumer threads. For each get() used to fetch a task, a subsequent call to task_done() tells the queue that the processing on the task is complete.

If a join() is currently blocking, it will resume when all items have been processed (meaning that a task_done() call was received for every item that had been put() into the queue).

Raises a ValueError if called more times than there were items placed in the queue.

New in version 2.5.

Queue. join ( )

Blocks until all items in the queue have been gotten and processed.

The count of unfinished tasks goes up whenever an item is added to the queue. The count goes down whenever a consumer thread calls task_done() to indicate that the item was retrieved and all work on it is complete. When the count of unfinished tasks drops to zero, join() unblocks.

New in version 2.5.

Example of how to wait for enqueued tasks to be completed:

def worker():
    while True:
        item = q.get()
        do_work(item)
        q.task_done()

q = Queue()
for i in range(num_worker_threads):
     t = Thread(target=worker)
     t.daemon = True
     t.start()

for item in source():
    q.put(item)

q.join()       # block until all tasks are done

python原生的list,dict等,都是not thread safe的。而queue,是线程安全的。Queue.Queue类即是一个队列的同步实现。今天有个需求,典型的“生产者消费者问题”,刚好可以用到queue,挺好用。

python queue模块有三种队列:
1、python queue模块的FIFO队列先进先出。
2、LIFO类似于堆。即先进后出。
3、还有一种是优先级队列级别越低越先出来。 

针对这三种队列分别有三个构造函数:
1、class Queue.Queue(maxsize) FIFO 
2、class Queue.LifoQueue(maxsize) LIFO 
3、class Queue.PriorityQueue(maxsize) 优先级队列 

介绍一下此包中的常用方法:

Queue.qsize() 返回队列的大小 
Queue.empty() 如果队列为空,返回True,反之False 
Queue.full() 如果队列满了,返回True,反之False
Queue.full 与 maxsize 大小对应 
Queue.get([block[, timeout]])获取队列,timeout等待时间 
Queue.get_nowait() 相当Queue.get(False)
非阻塞 Queue.put(item) 写入队列,timeout等待时间 
Queue.put_nowait(item) 相当Queue.put(item, False)
Queue.task_done() 在完成一项工作之后,Queue.task_done()函数向任务已经完成的队列发送一个信号
Queue.join() 实际上意味着等到队列为空,再执行别的操作

这个例子很好,参考至网上

#!/home/oracle/dbapython/bin/python
#encoding=utf-8
import threading
import time
from Queue import Queue

class Producer(threading.Thread):
    def run(self):
        global queue
        count = 0
        while True:
            for i in range(100):
                if queue.qsize() > 1000:
                     pass
                else:
                     count = count +1
                     msg = '生成产品'+str(count)
                     queue.put(msg)
                     print msg
            time.sleep(1)

class Consumer(threading.Thread):
    def run(self):
        global queue
        while True:
            for i in range(3):
                if queue.qsize() < 50:
                    pass
                else:
                    msg = self.name + '消费了 '+queue.get()
                    print msg
            time.sleep(1)

queue = Queue()

def test():
    for i in range(100):
        msg='初始产品'+str(i)
        print msg
        queue.put(msg)
    for i in range(2):
        p = Producer()
        p.start()
    for i in range(5):
        c = Consumer()
        c.start()
if __name__ == '__main__':
    test()

执行下,结果如下,自己试一下吧。

$ ./queue.py
初始产品0
初始产品1
初始产品2
初始产品3
初始产品4
初始产品5
初始产品6
初始产品7
初始产品8
...
初始产品92
初始产品93
初始产品94
初始产品95
初始产品96
初始产品97
初始产品98
初始产品99
生成产品1
生成产品2
生成产品3
生成产品4
 生成产品1
生成产品2
生成产品3
生成产品4
生成产品5
生成产品5
Thread-3消费了 初始产品0
生成产品6
生成产品7
生成产品6
生成产品8
Thread-3消费了 初始产品1
Thread-5消费了 初始产品2
Thread-4消费了 初始产品3
Thread-6消费了 初始产品4
生成产品7Thread-7消费了 初始产品5

生成产品9
Thread-3消费了 初始产品6
Thread-5消费了 初始产品7
Thread-4消费了 初始产品8
Thread-6消费了 初始产品9
Thread-7消费了 初始产品10
生成产品8
生成产品10
Thread-5消费了 初始产品11
Thread-4消费了 初始产品12
Thread-6消费了 初始产品13
Thread-7消费了 初始产品14
生成产品9生成产品11

生成产品10
生成产品12
生成产品11
生成产品13生成产品12
生成产品13
...
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
校园失物招领系统管理系统按照操作主体分为管理员和用户。管理员的功能包括字典管理、论坛管理、公告信息管理、失物招领管理、失物认领管理、寻物启示管理、寻物认领管理、用户管理、管理员管理。用户的功能等。该系统采用了Mysql数据库,Java语言,Spring Boot框架等技术进行编程实现。 校园失物招领系统管理系统可以提高校园失物招领系统信息管理问题的解决效率,优化校园失物招领系统信息处理流程,保证校园失物招领系统信息数据的安全,它是一个非常可靠,非常安全的应用程序。 ,管理员权限操作的功能包括管理公告,管理校园失物招领系统信息,包括失物招领管理,培训管理,寻物启事管理,薪资管理等,可以管理公告。 失物招领管理界面,管理员在失物招领管理界面中可以对界面中显示,可以对失物招领信息的失物招领状态进行查看,可以添加新的失物招领信息等。寻物启事管理界面,管理员在寻物启事管理界面中查看寻物启事种类信息,寻物启事描述信息,新增寻物启事信息等。公告管理界面,管理员在公告管理界面中新增公告,可以删除公告。公告类型管理界面,管理员在公告类型管理界面查看公告的工作状态,可以对公告的数据进行导出,可以添加新公告的信息,可以编辑公告信息,删除公告信息。
Python Queue模块是用来在线程间进行数据交换的常用模块。它包含了一些常用的队列操作函数,如创建队列对象、添加数据到队列、从队列中取值等。 在Python中,可以使用Queue模块来创建一个队列对象,并通过put()函数往队列中添加数据,通过get()函数从队列中取值。在多线程的情况下,可以使用队列来实现生产者-消费者模型,即一个线程往队列中添加数据,另外的线程从队列中取值。 队列模块提供了多种类型的队列,如FIFO(先进先出)队列和LIFO(后进先出)队列。可以通过参数maxsize来限制队列的长度,如果maxsize小于1表示队列长度无限制。另外,队列模块还提供了一些其他的函数,如返回队列大小、判断队列是否为空、判断队列是否已满等。 使用Queue模块可以方便地实现一些需求,比如爬虫的请求地址,可以将需要请求的URL放入队列中,然后通过多线程从队列中取值并进行请求。 总结起来,Python Queue模块是用来在线程间进行数据交换的模块,提供了创建队列对象、添加数据到队列、从队列中取值等常用的队列操作函数。可以通过队列模块实现生产者-消费者模型,并且支持不同类型的队列,如FIFO队列和LIFO队列。使用队列模块可以方便地实现一些需求,如爬虫的请求地址。<span class="em">1</span><span class="em">2</span><span class="em">3</span><span class="em">4</span>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值