/* @file event_bus.hpp * @brief Publish-subscribe event bus with shared_mutex for concurrent read access. * 发布-订阅事件总线,使用 shared_mutex 支持并发读访问。 * Copyright (c) 2026 dstalk contributors. GPLv3. */ #pragma once #include #include #include #include #include namespace dstalk { using EventHandler = std::function; // 轻量级发布-订阅事件总线 / Lightweight pub-sub event bus. // 读取者使用 shared_lock(emit),因此多个处理器可以并发分发; // 写入者使用 unique_lock(subscribe / unsubscribe)。 // Readers use shared_lock (emit) so multiple handlers can be dispatched // concurrently; writers use unique_lock (subscribe / unsubscribe). class EventBus { public: EventBus() = default; ~EventBus() = default; // 订阅事件,返回订阅ID / Subscribe to an event, returning a subscription id int subscribe(int event_type, EventHandler handler); // 取消订阅 / Unsubscribe by subscription id void unsubscribe(int subscription_id); // 发布事件 / Emit an event to all matching subscribers int emit(int event_type, const void* data); private: struct Subscription { int id; int event_type; EventHandler handler; }; mutable std::shared_mutex mutex_; // 读写锁:emit 用 shared,subscribe/unsubscribe 用 unique / RW lock: shared for emit, unique for subscribe/unsubscribe std::vector subscriptions_; // emit 时线性扫描;对少量订阅者足够 / Linear scan on emit; ok for small subscriber counts int next_id_ = 1; // 单调递增订阅 ID 计数器 / Monotonic subscription id counter }; } // namespace dstalk