diff options
| author | Ahmad Fatoum <[email protected]> | 2019-05-04 19:02:50 +0200 |
|---|---|---|
| committer | Ahmad Fatoum <[email protected]> | 2019-05-04 21:23:19 +0200 |
| commit | 6681fd7df27e4229518f51dc4929e909d9e94917 (patch) | |
| tree | 64cf665fbcc175b36d261cd05d3b7ccd6616000a | |
| parent | 53d9beb53486703ef66d0511b07bba32daf7dc60 (diff) | |
| download | raylib-6681fd7df27e4229518f51dc4929e909d9e94917.tar.gz raylib-6681fd7df27e4229518f51dc4929e909d9e94917.zip | |
examples: core_loading_thread: fix race condition
A plain variable is insuffecient for inter-thread communication. Both the
compiler and the processor may reorder accesses. The compiler could even
cache dataLoaded with the result that STATE_FINISHED becomes unreachable.
Fix this by using C11 atomic_bool, which guarantees sequential consistency.
This fixes #827.
| -rw-r--r-- | examples/core/core_loading_thread.c | 9 |
1 files changed, 5 insertions, 4 deletions
diff --git a/examples/core/core_loading_thread.c b/examples/core/core_loading_thread.c index 7b83c848..4ffc9d0b 100644 --- a/examples/core/core_loading_thread.c +++ b/examples/core/core_loading_thread.c @@ -15,10 +15,11 @@ #include "raylib.h" #include "pthread.h" // POSIX style threads management +#include <stdatomic.h> #include <time.h> // Required for clock() function -static bool dataLoaded = false; // Loading data semaphore +static atomic_bool dataLoaded = ATOMIC_VAR_INIT(false); // Data Loaded completion indicator static void *LoadDataThread(void *arg); // Loading data thread function declaration static int dataProgress = 0; // Data progress accumulator @@ -59,7 +60,7 @@ int main() break; case STATE_LOADING: framesCounter++; - if (dataLoaded) + if (atomic_load(&dataLoaded)) { framesCounter = 0; state = STATE_FINISHED; @@ -69,7 +70,7 @@ int main() if (IsKeyPressed(KEY_ENTER)) { // Reset everything to launch again - dataLoaded = false; + atomic_store(&dataLoaded, false); dataProgress = 0; state = STATE_WAITING; } @@ -130,7 +131,7 @@ static void *LoadDataThread(void *arg) } // When data has finished loading, we set global variable - dataLoaded = true; + atomic_store(&dataLoaded, true); return NULL; } |
