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.
This commit is contained in:
Arthur Sonzogni 2022-07-04 23:34:37 +02:00 committed by GitHub
parent 0abaab6268
commit 57da24dfdb
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -1,5 +1,6 @@
#include <stddef.h> // for size_t #include <stddef.h> // for size_t
#include <array> // for array #include <array> // for array
#include <atomic> // for atomic
#include <chrono> // for operator""s, chrono_literals #include <chrono> // for operator""s, chrono_literals
#include <cmath> // for sin #include <cmath> // for sin
#include <functional> // for ref, reference_wrapper, function #include <functional> // for ref, reference_wrapper, function
@ -499,13 +500,18 @@ int main(int argc, const char* argv[]) {
}); });
}); });
bool refresh_ui_continue = true; std::atomic<bool> refresh_ui_continue = true;
std::thread refresh_ui([&] { std::thread refresh_ui([&] {
while (refresh_ui_continue) { while (refresh_ui_continue) {
using namespace std::chrono_literals; using namespace std::chrono_literals;
std::this_thread::sleep_for(0.05s); std::this_thread::sleep_for(0.05s);
shift++; // The |shift| variable belong to the main thread. `screen.Post(task)`
screen.PostEvent(Event::Custom); // 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);
} }
}); });