From 15da9cdc186e1559c0faa6cbb79a8349a305429f Mon Sep 17 00:00:00 2001 From: ArthurSonzogni Date: Sat, 2 Feb 2019 16:28:44 +0100 Subject: [PATCH] Improve ScreenInteractive wait function. --- examples/component/menu.cpp | 2 +- .../ftxui/component/screen_interactive.hpp | 2 +- src/ftxui/component/screen_interactive.cpp | 22 ++++++++----------- 3 files changed, 11 insertions(+), 15 deletions(-) diff --git a/examples/component/menu.cpp b/examples/component/menu.cpp index 256a46d..a33ace4 100644 --- a/examples/component/menu.cpp +++ b/examples/component/menu.cpp @@ -7,7 +7,7 @@ int main(int argc, const char* argv[]) { using namespace ftxui; - auto screen = ScreenInteractive::FixedSize(30, 3); + auto screen = ScreenInteractive::TerminalOutput(); Menu menu; menu.entries = {L"entry 1", L"entry 2", L"entry 3"}; diff --git a/include/ftxui/component/screen_interactive.hpp b/include/ftxui/component/screen_interactive.hpp index 65f42ba..8d1043e 100644 --- a/include/ftxui/component/screen_interactive.hpp +++ b/include/ftxui/component/screen_interactive.hpp @@ -40,7 +40,7 @@ class ScreenInteractive : public Screen { Dimension dimension_ = Dimension::Fixed; ScreenInteractive(int dimx, int dimy, Dimension dimension); - std::condition_variable events_queue_wait; + std::condition_variable events_queue_cv; std::mutex events_queue_mutex; std::queue events_queue; std::atomic quit_ = false; diff --git a/src/ftxui/component/screen_interactive.cpp b/src/ftxui/component/screen_interactive.cpp index d883d15..3cb4a4a 100644 --- a/src/ftxui/component/screen_interactive.cpp +++ b/src/ftxui/component/screen_interactive.cpp @@ -71,25 +71,21 @@ ScreenInteractive ScreenInteractive::FitComponent() { return ScreenInteractive(0, 0, Dimension::FitComponent); } -void ScreenInteractive::PostEvent(Event event) { +void ScreenInteractive::PostEvent(Event event) { std::unique_lock lock(events_queue_mutex); events_queue.push(event); - events_queue_wait.notify_one(); + events_queue_cv.notify_one(); } void ScreenInteractive::EventLoop(Component* component) { - bool handled = 0; - for (;;) { - std::unique_lock lock(events_queue_mutex); - while (!events_queue.empty()) { - component->OnEvent(events_queue.front()); - events_queue.pop(); - handled = true; - } + std::unique_lock lock(events_queue_mutex); + while (!quit_ && events_queue.empty()) + events_queue_cv.wait(lock); - if (handled) - return; - events_queue_wait.wait(lock); + // After the wait, we own the lock. + while (!events_queue.empty()) { + component->OnEvent(events_queue.front()); + events_queue.pop(); } }