1. 队列(Queue)基础概念
队列(Queue)是一种先进先出(FIFO, First In First Out)的线性数据结构,类似于现实生活中的排队。在Python中,队列是线程安全的,常用于多线程编程中的生产者-消费者模型。
2. Python标准库中的队列模块
Python的queue模块提供了多种队列实现:
2.1 Queue
基本的先进先出队列:
import queue 创建队列 q = queue.Queue(maxsize=3) # 设置最大容量 入队 q.put('A') q.put('B') q.put('C') 出队 print(q.get()) # 输出: A print(q.get()) # 输出: B 队列大小 print(q.qsize()) # 输出: 12.2 LifoQueue
后进先出队列(栈):
import queue lifo_q = queue.LifoQueue() lifo_q.put('A') lifo_q.put('B') lifo_q.put('C') print(lifo_q.get()) # 输出: C(后进先出)2.3 PriorityQueue
优先级队列:
import queue pri_q = queue.PriorityQueue() pri_q.put((3, 'Low priority')) pri_q.put((1, 'High priority')) pri_q.put((2, 'Medium priority')) print(pri_q.get()) # 输出: (1, 'High priority') print(pri_q.get()) # 输出: (2, 'Medium priority')3. collections.deque:双端队列
collections.deque是Python中高效的双端队列实现,支持从两端快速添加和删除元素:
from collections import deque 创建双端队列 d = deque(['B', 'C', 'D']) 从左侧添加 d.appendleft('A') print(d) # 输出: deque(['A', 'B', 'C', 'D']) 从右侧添加 d.append('E') print(d) # 输出: deque(['A', 'B', 'C', 'D', 'E']) 从左侧弹出 print(d.popleft()) # 输出: A 从右侧弹出 print(d.pop()) # 输出: E 限制最大长度 limited_d = deque(maxlen=3) limited_d.extend([1, 2, 3]) limited_d.append(4) print(limited_d) # 输出: deque([2, 3, 4], maxlen=3)4. 队列在多线程中的应用
队列是线程间通信的安全方式:
import queue import threading import time def producer(q): for i in range(5): time.sleep(0.5) q.put(f'产品{i}') print(f'生产者生产: 产品{i}') def consumer(q): while True: item = q.get() if item is None: # 终止信号 break print(f'消费者消费: {item}') q.task_done() 创建队列 q = queue.Queue() 创建线程 prod_thread = threading.Thread(target=producer, args=(q,)) cons_thread = threading.Thread(target=consumer, args=(q,)) 启动线程 prod_thread.start() cons_thread.start() 等待生产者完成 prod_thread.join() 发送终止信号 q.put(None) cons_thread.join()5. 高级队列应用与拓展
5.1 异步队列(asyncio.Queue)
用于异步编程的队列:
import asyncio async def producer(queue): for i in range(3): await asyncio.sleep(1) await queue.put(f'异步任务{i}') print(f'生产: 异步任务{i}') async def consumer(queue): while True: item = await queue.get() if item is None: break print(f'消费: {item}') queue.task_done() async def main(): queue = asyncio.Queue() # 创建生产者和消费者任务 prod_task = asyncio.create_task(producer(queue)) cons_task = asyncio.create_task(consumer(queue)) 等待生产者完成 await prod_task 发送终止信号 await queue.put(None) await cons_task 等待队列清空 await queue.join() asyncio.run(main())5.2 消息队列中间件集成
Python可以集成RabbitMQ、Redis等消息队列:
# RabbitMQ示例(需要pika库) import pika 连接RabbitMQ connection = pika.BlockingConnection( pika.ConnectionParameters('localhost') ) channel = connection.channel() 声明队列 channel.queue_declare(queue='hello') 发送消息 channel.basic_publish( exchange='', routing_key='hello', body='Hello RabbitMQ!' ) print("消息已发送") connection.close()5.3 自定义优先级队列
import heapq class CustomPriorityQueue: def init(self): self._queue = [] self._index = 0 def push(self, item, priority): heapq.heappush(self._queue, (priority, self._index, item)) self._index += 1 def pop(self): return heapq.heappop(self._queue)[-1] def is_empty(self): return len(self._queue) == 0 使用示例 pq = CustomPriorityQueue() pq.push('任务A', 2) pq.push('任务B', 1) pq.push('任务C', 3) print(pq.pop()) # 输出: 任务B(优先级最高) print(pq.pop()) # 输出: 任务A6. 性能比较与选择建议
| 队列类型 | 特点 | 适用场景 |
|---|---|---|
queue.Queue | 线程安全,FIFO | 多线程编程,生产者-消费者 |
queue.LifoQueue | 线程安全,LIFO | 需要栈结构的线程安全场景 |
queue.PriorityQueue | 线程安全,按优先级 | 任务调度,优先级处理 |
collections.deque | 高效双端操作 | 需要频繁两端操作,单线程场景 |
asyncio.Queue | 异步支持 | 异步编程,协程间通信 |
7. 最佳实践与注意事项
- 线程安全:在多线程环境中使用
queue模块的队列 - 避免死锁:合理设置超时时间,使用
put(timeout=...)和get(timeout=...) - 资源管理:及时调用
task_done()和join() - 性能考虑:单线程场景优先使用
collections.deque - 错误处理:处理
queue.Empty和queue.Full异常
8. 总结
Python提供了丰富的队列实现,从基础的queue.Queue到高效的collections.deque,再到支持异步的asyncio.Queue。选择适合的队列类型可以显著提升程序性能和可维护性。在实际开发中,应根据具体需求(线程安全、性能要求、功能特性)选择合适的队列实现。