mirror of
				https://github.com/ArthurSonzogni/FTXUI.git
				synced 2025-10-31 18:48:11 +08:00 
			
		
		
		
	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:
		| @@ -1,5 +1,6 @@ | ||||
| #include <stddef.h>    // for size_t | ||||
| #include <array>       // for array | ||||
| #include <atomic>      // for atomic | ||||
| #include <chrono>      // for operator""s, chrono_literals | ||||
| #include <cmath>       // for sin | ||||
| #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([&] { | ||||
|     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); | ||||
|     } | ||||
|   }); | ||||
|  | ||||
|   | ||||
		Reference in New Issue
	
	Block a user
	 Arthur Sonzogni
					Arthur Sonzogni