[Python]Queue -- A synchronized queue class

Python Queue模块详解
本文介绍了Python中的Queue模块,该模块实现了一个多生产者、多消费者的第一入先出(FIFO)队列,特别适用于多线程编程中多个线程间安全地交换信息。文章详细解释了Queue类的构造方法及主要方法,如put、get等,并说明了队列满或空时可能抛出的异常。

  The Queue module implements a multi-producer, multi-consumer FIFO queue. It is especially useful in threads 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.  

  The Queue module defines the following class and exception:

 

class Queue( maxsize)
Constructor for the class. 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.

 

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

 

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

 

Queue Objects

  Class Queue implements queue objects and has the methods described below. This class can be derived from in order to implement other queue organizations (e.g. stack) but the inheritable interface is not described here. See the source code for details. The public methods are:

 

qsize( )
Return the approximate size of the queue. Because of multithreading semantics, this number is not reliable.

 

empty( )
Return True if the queue is empty, False otherwise. Becauseof multithreading semantics, this is not reliable.

 

full( )
Return True if the queue is full, False otherwise. Because of multithreading semantics, this is not reliable.

 

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.

 

 

put_nowait( item)
Equivalent to put(item, False).

 

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.

 

 

get_nowait( )
Equivalent to get(False).
### 关于队列的数据结构及其应用 队列是一种遵循“先进先出”(FIFO:First-In First-Out)原则的线性数据结构[^1]。这意味着最早进入队列中的元素会最先被移除。以下是几个常见的队列编程题目和实训内容,帮助理解并实践队列的应用。 #### 示例一:模拟银行排队系统 编写一个程序来模拟客户在银行柜台前排队的情况。假设每次只有一个柜员处理客户的请求,每位客户的服务时间不同。可以使用队列存储等待服务的客户列表,并按顺序依次提供服务。 ```cpp #include <iostream> #include <queue> using namespace std; struct Customer { int id; int serviceTime; // 单位秒 }; void simulateBankQueue(queue<Customer> customers) { while (!customers.empty()) { Customer currentCustomer = customers.front(); cout << "Processing customer ID: " << currentCustomer.id << ", Service Time: " << currentCustomer.serviceTime << endl; // Simulate the processing time (for simplicity, just output it here). this_thread::sleep_for(chrono::seconds(currentCustomer.serviceTime)); customers.pop(); // Remove processed customer from queue. } } int main() { queue<Customer> bankQueue; // Add some sample customers to the queue. bankQueue.push({1, 5}); // Customer with ID=1 and needs 5 seconds of service. bankQueue.push({2, 3}); bankQueue.push({3, 7}); simulateBankQueue(bankQueue); } ``` 此代码展示了如何利用标准库 `std::queue` 来实现简单的银行排队逻辑[^2]。 --- #### 示例二:广度优先搜索(BFS) 队列常用于图遍历算法中,比如广度优先搜索(BFS)。通过维护一个节点访问记录以及待探索邻居节点的队列,能够有效地完成从起始点到目标点最短路径的查找。 ```python from collections import deque def bfs(graph, start_node): visited = set() queue = deque([start_node]) result_path = [] while queue: node = queue.popleft() if node not in visited: visited.add(node) result_path.append(node) # Enqueue all unvisited neighbors. for neighbor in graph[node]: if neighbor not in visited: queue.append(neighbor) return result_path if __name__ == "__main__": adjacency_list_graph = { 'A': ['B', 'C'], 'B': ['D', 'E'], 'C': ['F'], 'D': [], 'E': ['F'], 'F': [] } path = bfs(adjacency_list_graph, 'A') print("Visited nodes:", path) ``` 上述 Python 脚本实现了基于队列的 BFS 算法,适用于无向连通图上的节点遍历操作。 --- #### 示例三:循环缓冲区设计 创建一个固定大小的支持动态入队与出队功能的环形缓冲器类。此类特别适合资源受限环境下的高效内存管理场景。 ```java public class CircularBuffer<T> { private final T[] buffer; private int head = 0; private int tail = 0; private boolean isFull = false; @SuppressWarnings("unchecked") public CircularBuffer(int capacity) { buffer = (T[]) new Object[capacity]; } public synchronized void enqueue(T item) throws InterruptedException { if (isFull) throw new IllegalStateException("The circular buffer is full."); buffer[tail++] = item; if(tail >= buffer.length){ tail %= buffer.length; } if(head == tail){ isFull=true; } } public synchronized T dequeue(){ if(!isFull && head==tail){ throw new IllegalStateException("The circular buffer is empty."); }else{ T data =buffer[head++]; if(head>=buffer.length){ head%=buffer.length; } isFull=false; return data; } } } ``` 该 Java 类提供了基本的功能接口以支持高效的 FIFO 行为,在多线程环境中尤其有用。 ---
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值