以下是根据您的要求修改后的代码。原代码使用 asyncio 来异步处理事件和并行执行订阅者(subscribers)。现在,我将它改为使用线程来并行执行所有订阅者的回调,而不使用任何异步(async/await)功能。核心变化包括:
- 移除异步:将所有 async 函数(如 EventBus.publish 和 Subscriber.handle_event)改为同步函数。
- 使用线程并行执行:在 EventBus.publish 方法中使用
concurrent.futures.ThreadPoolExecutor 来创建线程池,从而并行运行每个订阅者的回调函数。
- 假设 ping_host 为同步函数:原 ping_host 是异步的,我会提供一个同步版本的模拟实现(例如,使用 time.sleep 来模拟网络延迟)。如果您有真实的同步 ping_host 函数,请替换它。
- 修改 main 函数:原 main 是异步的,现在改为同步函数,并使用常规的执行方式。
关键修改说明:
-
EventBus.publish:
- 改为同步方法。
- 使用 ThreadPoolExecutor 来提交每个回调任务到线程池中。
- 等待所有线程完成(使用 future.result()),以确保 publish 方法在所有订阅者处理完后返回。
-
Subscriber.handle_event:
- 改为同步函数,移除 await。
- ping_host 现在是同步的,因此可以直接调用。
-
ping_host:
- 提供一个同步模拟版本,使用 time.sleep 来模仿延迟。
-
main 函数:
完整代码:
from loguru import logger
import threading
from concurrent.futures import ThreadPoolExecutor
import time # 用于模拟同步延迟
# 模拟的同步 ping_host 函数
def ping_host(host):
logger.info(f"Starting ping to {host}...")
# 模拟网络延迟(例如,随机延迟 1-3 秒)
delay = 1 + threading.local().random.uniform(0, 2) # 简单模拟不同延迟
time.sleep(delay) # 同步等待
logger.info(f"Ping to {host} completed in {delay:.2f} seconds")
return f"Ping result for {host}"
class EventBus:
def __init__(self):
self._subscribers = {}
def subscribe(self, event_type, callback):
if event_type not in self._subscribers:
self._subscribers[event_type] = []
self._subscribers[event_type].append(callback)
def unsubscribe(self, event_type, callback):
if event_type in self._subscribers:
try:
self._subscribers[event_type].remove(callback)
except ValueError:
logger.warning(f"Callback not subscribed for event {event_type}")
def publish(self, event_type, *args, **kwargs):
if event_type in self._subscribers:
with ThreadPoolExecutor() as executor: # 创建线程池
futures = [] # 存储 future 对象
for callback in self._subscribers[event_type]:
# 提交任务到线程池中并行执行
future = executor.submit(callback, event_type, *args, **kwargs)
futures.append(future)
# 等待所有任务完成,并处理可能的异常
for future in futures:
try:
future.result() # 阻塞直到任务完成
except Exception as e:
logger.error(f"Error in subscriber task: {e}")
class Subscriber:
def __init__(self, name):
self.name = name
def handle_event(self, event_type, data):
logger.info(f"Subscriber {self.name} received event '{event_type}' with data: {data}")
if event_type == "power_on":
logger.info(f"{self.name}: Handling 'power_on' event.")
elif event_type == "power_off":
logger.info(f"{self.name}: Handling 'power_off' event.")
elif event_type == "power_restart":
logger.info(f"{self.name}: Handling 'power_restart' event.")
ping_host(data) # 现在是同步调用
else:
logger.warning(f"{self.name}: Unknown event type: {event_type}")
def main():
event_bus = EventBus()
subscriber1 = Subscriber("Subscriber1")
subscriber2 = Subscriber("Subscriber2")
event_bus.subscribe("power_restart", subscriber1.handle_event)
event_bus.subscribe("power_restart", subscriber2.handle_event)
logger.info("Publishing 'power_restart' event...")
start_time = time.time() # 记录开始时间
event_bus.publish("power_restart", "www.baidu.com") # 同步发布
end_time = time.time() # 记录结束时间
logger.info(f"All subscribers completed in {end_time - start_time:.2f} seconds")
if __name__ == '__main__':
main()
运行结果说明:
注意事项:
- 线程安全:这个实现使用了 ThreadPoolExecutor,它会自动管理线程池。如果有更多订阅者,线程池会高效地处理它们(默认线程数基于 CPU 核心)。
- 异常处理:在 publish 方法中,我添加了 try-except 来捕获每个线程中的异常,确保一个订阅者的错误不会影响其他订阅者。
- 性能:线程并行适合 I/O 密集型任务(如网络 ping),但如果任务是 CPU 密集型的,可能会有 GIL(Global Interpreter Lock)的限制。
- 随机延迟模拟:在 ping_host 中,我使用了 threading.local().random.uniform() 来模拟每个线程的独立随机延迟。如果您需要真实的随机数,请确保在每个线程中正确初始化。
- 如果 ping_host 是异步的:如果您的 ping_host 必须保持异步,这会更复杂,因为您需要在每个线程中运行一个 asyncio 事件循环(使用 asyncio.run())。但根据您的要求,我已将其改为完全同步。如果需要混合 async 和线程,请提供更多细节。
这个版本应该满足您的需求:不使用 async,而是使用线程来并行执行所有 subscribers。如果有任何进一步调整,请随时告知!