24#include <shared_mutex>
27#include <unordered_map>
57 running_.store(
true, std::memory_order_release);
64 running_.store(
false, std::memory_order_release);
71 return running_.load(std::memory_order_acquire);
80 template<
typename Event>
81 uint64_t
subscribe(std::function<
void(
const Event&)> handler) {
82 std::unique_lock lock(
mutex_);
84 auto type = std::type_index(
typeid(Event));
87 handlers.push_back({id, [handler](
const void*
event) {
88 handler(*
static_cast<const Event*
>(
event));
99 std::unique_lock lock(
mutex_);
100 for (
auto& [type, handlers] :
handlers_) {
102 std::remove_if(handlers.begin(), handlers.end(),
104 return entry.id == subscription_id;
115 template<
typename Event>
119 std::shared_lock lock(
mutex_);
120 auto type = std::type_index(
typeid(Event));
123 for (
const auto& entry : it->second) {
124 entry.handler(&
event);
132 template<
typename Event>
134 std::shared_lock lock(
mutex_);
135 auto type = std::type_index(
typeid(Event));
138 return it->second.size();
147 std::unique_lock lock(
mutex_);
160 std::unordered_map<std::type_index, std::vector<HandlerEntry>>
handlers_;
Thread-safe event bus for publish/subscribe pattern.
bool is_running() const
Check if the event bus is running.
std::atomic< bool > running_
void publish(const Event &event)
Publish an event to all subscribers.
void start()
Start the event bus.
std::atomic< uint64_t > next_id_
void clear()
Clear all subscriptions.
std::unordered_map< std::type_index, std::vector< HandlerEntry > > handlers_
void stop()
Stop the event bus.
size_t subscriber_count() const
Get the number of subscribers for an event type.
uint64_t subscribe(std::function< void(const Event &)> handler)
Subscribe to events of a specific type.
void unsubscribe(uint64_t subscription_id)
Unsubscribe from events.
uint64_t subscription_id
Type alias for subscription ID.
Generic event structure for the event bus.
std::function< void(const void *)> handler