From 57da24dfdbaf37b54c39afd3e34f6c5d59ceee62 Mon Sep 17 00:00:00 2001 From: Arthur Sonzogni Date: Mon, 4 Jul 2022 23:34:37 +0200 Subject: [PATCH] Fix homescreen example thread safety. (#431) This addresses and fix: https://github.com/ArthurSonzogni/FTXUI/issues/430 This patchs makes |shift| to be read and written on the same thread. We request the update to be made via a task posted on the main thread. This patch has no real consequence, the previous behavior was fine. I hope it will help users not to have thread safety issue and better understand they can post tasks this way. --- examples/component/homescreen.cpp | 12 +++++++++--- 1 file changed, 9 insertions(+), 3 deletions(-) diff --git a/examples/component/homescreen.cpp b/examples/component/homescreen.cpp index d8af183..2f5370a 100644 --- a/examples/component/homescreen.cpp +++ b/examples/component/homescreen.cpp @@ -1,5 +1,6 @@ #include // for size_t #include // for array +#include // for atomic #include // for operator""s, chrono_literals #include // for sin #include // for ref, reference_wrapper, function @@ -499,13 +500,18 @@ int main(int argc, const char* argv[]) { }); }); - bool refresh_ui_continue = true; + std::atomic refresh_ui_continue = true; std::thread refresh_ui([&] { while (refresh_ui_continue) { using namespace std::chrono_literals; std::this_thread::sleep_for(0.05s); - shift++; - screen.PostEvent(Event::Custom); + // The |shift| variable belong to the main thread. `screen.Post(task)` + // will execute the update on the thread where |screen| lives (e.g. the + // main thread). Using `screen.Post(task)` is threadsafe. + screen.Post([&] { shift++; }); + // After updating the state, request a new frame to be drawn. This is done + // by simulating a new "custom" event to be handled. + screen.Post(Event::Custom); } });