# -*- coding: utf-8 -*- # File: message_queue.py # Purpose: 提供线程安全的消息队列,用于模块间的异步通信。 import queue import threading from typing import Any, Optional from datetime import datetime class MessageQueue: def __init__(self, maxsize: int = 1000): self.queue = queue.Queue(maxsize=maxsize) self.lock = threading.Lock() self.callbacks = [] def put(self, message: Any): """将消息放入队列""" with self.lock: try: self.queue.put_nowait({ 'message': message, 'timestamp': datetime.now() }) self._notify_callbacks() except queue.Full: print("消息队列已满,丢弃消息") def get(self, block: bool = True, timeout: Optional[float] = None) -> Optional[dict]: """从队列中获取消息""" try: return self.queue.get(block=block, timeout=timeout) except queue.Empty: return None def register_callback(self, callback: callable): """注册消息回调函数""" with self.lock: self.callbacks.append(callback) def unregister_callback(self, callback: callable): """注销消息回调函数""" with self.lock: if callback in self.callbacks: self.callbacks.remove(callback) def _notify_callbacks(self): """通知所有注册的回调函数""" for callback in self.callbacks: try: callback() except Exception as e: print(f"回调函数执行失败: {str(e)}") def clear(self): """清空消息队列""" with self.lock: while not self.queue.empty(): try: self.queue.get_nowait() except queue.Empty: break def size(self) -> int: """获取队列大小""" return self.queue.qsize() def is_empty(self) -> bool: """检查队列是否为空""" return self.queue.empty()