python关于queue模块

1.概述

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.

队列模块实现了多生产者, 多消费者队列; 它在线程编程中要求多个线程间安全的交换信息时特别有用, Queue类实现了所有所需的锁定语义,它取决于python支持的线程的可用性;

1)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.
2)Internally, those three types of queues use locks to temporarily block competing threads; however, they are not designed to handle reentrancy within a thread.
3)In addition, the module implements a “simple” FIFO queue type where specific implementations can provide additional guarantees in exchange for the smaller functionality.

模块实现了三种形式的队列, 只是在放入的数据取出顺序上有所不同: 1.FIFO: 先进先出; 2. LIFO: 后进先出; 3.priority:数据进行排序, 最低数字优先级的先被取出;

在内部, 队列是通过锁来实现暂时阻塞竞争线程的, 但队列不是用来处理线程内的重用的;

另外, 这个模块还实现了一种简单的FIFO queue类型, 可以对特定的处理实现额外的保证但同时功能变少了;

2.该模块下的类和异常
(1)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.

FIFO的构造函数; maxsize参数是一个整数,规定了可以放入队列中的元素个数的上限; 如果size已满, 那再输入会阻塞, 直到队列中的元素被消耗; 如果maxsize是0,或小于0, 队列size是无限的

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

LIFO队列的构造函数; 其余同上;

(3)class queue.PriorityQueue(maxsize=0)

1)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.
2)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).
3)If the data elements are not comparable, the data can be wrapped in a class that ignores the data item and only compares the priority number

priority queue的构造函数, 其余同上;

最低优先级数字的条目被最先取出(最低优先级数字的条目就是sorted(list(entries))[0]的结果) ; 典型的条目格式如下(priority_number, data)
注意: 所有放入队列的元素间必须可互相比较

???如果数据元素不可比较,那数据可以被封装到一个忽略数据只比较priority number的类中进行处理:

from dataclasses import dataclass, field
from typing import Any

@dataclass(order=True)
class PrioritizedItem:
    priority: int
    item: Any=field(compare=False)  

(4)class queue.SimpleQueue

Constructor for an unbounded FIFO queue. Simple queues lack advanced functionality such as task tracking.

无界FIFO的构造函数; 缺少如任务追踪等高级功能的简单队列

(5)exception queue.Empty

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

当队列对象为空时调用非阻塞的get()或get_notwait()方法时抛出该异常

(6)exception queue.Full

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

当队列已满并调用非阻塞的put()或put_nowait()方法时抛出该异常

3.队列对象

(1)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

该方法返回队列的大致大小.??? 返回值大于0不保证get()不会阻塞, 返回值小于最大条目数不保证put()不会阻塞. 要你何用?

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

如果队列为空则返回True; 同样仅作参考,不保证get()和put()不会阻塞.

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

如果队列已满返回True. 同样仅作参考…

(4)Queue.put(item, block=True, timeout=None)

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

将一个条目放入队列; 如果block参数为True, 那将一直阻塞直到队列中有空位, (timeout参数给定的话则最多阻塞给定的时间然后就抛出Full异常); block如果为False, 则队列如满则立即抛出异常, 无视timeout参数.

Queue.put_nowait(item)

Equivalent to put(item, False).

相当于put(item, False)

(5)Queue.get(block=True, timeout=None)

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

返回队列中条目的同时从队列中移除它; 如果参数block参数为True, 那将一直阻塞直到可从队列中取出数据 (timeout参数给出则最多阻塞给定的时间,如果没有获得数据则抛出empty异常); 如果参数block设为False则没有获得数据立即抛出异常,无视timeout参数.

Queue.get_nowait()

Equivalent to get(False).

相当于get(False)

(6)Queue.task_done()

1)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.
2)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).
3)Raises a ValueError if called more times than there were items placed in the queue.

表明前面的队列任务已完成. 被队列消费者线程使用; 对于获取任务的每个get(), 随后调用task_done()来告诉队列任务已处理完成;

如果join()方法目前正在阻塞, 那么当所有条目都已处理后(每个已放入队列中的元素收到task_done)它就会恢复

如果调用次数超出队列中曾经放入的元素个数

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

阻塞直到队列中的所有元素已经被获取并处理; 每当元素被放入队列, 未完成的任务数就会增加; 每当调用task_done()方法, 意味着元素被取出并处理完成, 未完成任务数就会减少; 当未完成任务数减少到0, join()就停止阻塞;

注意:join()是否阻塞只跟task_done()的数量有关,队列中几个元素就有几个相应的task_done(), 否则就算元素都被取走也会一直阻塞, 同样元素没有取完但task_done()数量够了也会变为非阻塞,队列长用于生产者消费者模型
使用实例:

import threading
import time
import queue


def test1():
    time.sleep(2)
    print('test1 starting')
    l.put('shit', True, None)  # 返回None
    l.put(123)
    l.join()  # 只要task_done()数量小于队列中元素数量就会阻塞
    print(l.qsize(), l.empty(), l.full())
    print('test1 ending')


def test2():
    print('test2 starting')
    data = l.get(True, None)
    print(data)
    time.sleep(1)
    l.task_done()
    l.task_done()  # 返回None
    print('test2 ending')


def test3():
    time.sleep(4)
    print('test3 starting')
    l1.put((5, 2))
    l1.put((3, 'happy'))  # 优先级队列必须是互相间可比较元素
    print('test3 ending')


def test4():
    time.sleep(4)
    print('test4 starting')
    print(l1.get())
    print('test4 ending')


a = threading.Thread(target=test1)
b = threading.Thread(target=test2)
c = threading.Thread(target=test3)
d = threading.Thread(target=test4)

l = queue.Queue()
l1 = queue.PriorityQueue()

a.start()
b.start()
c.start()
d.start()

print('main ending')

#result
test2 starting
main ending
test1 starting
shit
test2 ending
1 False False
test1 ending
test3 starting
test3 ending
test4 starting
(3, 'happy')
test4 ending

4.simple Queue对象的方法
(1)

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

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

SimpleQueue.put_nowait(item)
Equivalent to put(item), provided for compatibility with Queue.put_nowait().

SimpleQueue.get(block=True, timeout=None)
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).

SimpleQueue.get_nowait()
Equivalent to get(False).

上述五种方法与Queue用法一样;

(2)
SimpleQueue.put(item, block=True, timeout=None)

Put item into the queue. The method never blocks and always succeeds (except for potential low-level errors such as failure to allocate memory). The optional args block and timeout are ignored and only provided for compatibility with Queue.put().

CPython implementation detail: This method has a C implementation which is reentrant. That is, a put() or get() call can be interrupted by another put() call in the same thread without deadlocking or corrupting internal state inside the queue. This makes it appropriate for use in destructors such as __ del__ methods or weakref callbacks.

put()方法有区别,见上面说明,较少用到

  • 1
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值