From ea8840291cdf66784c6a2cb465b63ccfb5483c38 Mon Sep 17 00:00:00 2001 From: Matthias Schiffer Date: Wed, 24 Sep 2014 01:38:30 +0200 Subject: New event-driven goodness --- src/control/EventBus.hpp | 58 +++++++++++++++++++++++++++++++++++------------- 1 file changed, 43 insertions(+), 15 deletions(-) (limited to 'src/control/EventBus.hpp') diff --git a/src/control/EventBus.hpp b/src/control/EventBus.hpp index ae4603f..7284883 100644 --- a/src/control/EventBus.hpp +++ b/src/control/EventBus.hpp @@ -27,12 +27,16 @@ #pragma once -#include "Event.hpp" +#include "TimeProvider.hpp" +#include +#include +#include #include +#include #include -#include #include +#include namespace RPGEdit { @@ -40,35 +44,59 @@ namespace RPGEdit { namespace Control { class EventBus { -private: - typedef std::pair> event_entry; +public: + typedef std::function Event; + typedef std::pair EventEntry; - static bool compare_events(const event_entry &e1, const event_entry &e2) { +private: + static bool compare_events(const EventEntry &e1, const EventEntry &e2) { return e1.first > e2.first; } - std::priority_queue, bool (*)(const event_entry &, const event_entry &)> events; + std::priority_queue, bool (*)(const EventEntry &, const EventEntry &)> events; + + std::mutex mutex; + std::condition_variable cond; public: EventBus() : events(compare_events) { } - void enqueue(const std::shared_ptr &event, uint64_t time) { - events.push(std::pair>(time, event)); + void enqueue(const Event &event, uint64_t time) { + std::lock_guard lock(mutex); + events.push(EventEntry(time, event)); + cond.notify_one(); } - std::pair> get(uint64_t time) { - if (events.empty()) - return std::make_pair>(std::numeric_limits::max(), nullptr); + EventEntry get(TimeProvider *timeProvider) { + std::unique_lock lock(mutex); + + while (true) { + if (events.empty()) { + cond.wait(lock); + continue; + } - std::pair> top = events.top(); + EventEntry top = events.top(); + uint64_t time = timeProvider->now(); + + if (top.first > time) { + cond.wait_for(lock, std::chrono::milliseconds(top.first - time)); + continue; + } - if (top.first <= time) { events.pop(); return top; } - else - return std::pair>(top.first, std::shared_ptr()); + } + + uint64_t peek() { + std::lock_guard lock(mutex); + + if (events.empty()) + return std::numeric_limits::max(); + + return events.top().first; } }; -- cgit v1.2.3