Skip to content

Commit

Permalink
VIDEO: Defensive code.
Browse files Browse the repository at this point in the history
OS thread scheduling is variable and non-determinisitic. Defensive code
to check that startup_state isn't STARTUP_COMPLETE before waiting for
sdl_intialized_cond.

- main() executes the deferred startup, but the simulator thread hasn't
  been scheduled and isn't (yet) waiting for the sdl_initialized_cond
  condition to signal.

- STARTUP_COMPLETE is a reasonable indicator to the simulator thread
  that waiting for sdl_intialized_cond is not useful.

Bracket the entirety of the function with sdl_initialized_mutex.
  • Loading branch information
bscottm committed Apr 6, 2024
1 parent 26b0bb3 commit 6d60630
Showing 1 changed file with 13 additions and 7 deletions.
20 changes: 13 additions & 7 deletions sim_video.c
Original file line number Diff line number Diff line change
Expand Up @@ -911,19 +911,25 @@ static void maybe_event_only_initialization()

static void do_deferred_initialization()
{
enum DeferredStartup_enum current_state = SDL_AtomicGet(&startup_state);

if (current_state != STARTUP_COMPLETE) {
SDL_LockMutex(sdl_initialized_mutex);
SDL_LockMutex(sdl_initialized_mutex);

if (SDL_AtomicGet(&startup_state) != STARTUP_COMPLETE) {
/* Signal the waiting main thread */
if (main_event_cond != NULL)
SDL_CondSignal(main_event_cond);

/* Wait for the signal that main() is in the event queue... */
SDL_CondWait(sdl_initialized_cond, sdl_initialized_mutex);
SDL_UnlockMutex(sdl_initialized_mutex);
/* Wait for the signal that main() is in the event queue...
*
* Defensive code: OS thread scheduling can prevent us from receiving
* the condition variable's signal, i.e., main() executes the
* SDL_CondSignal(), but we're not actually waiting for it yet.
*/
while (SDL_AtomicGet(&startup_state) != STARTUP_COMPLETE) {
SDL_CondWait(sdl_initialized_cond, sdl_initialized_mutex);
}
}

SDL_UnlockMutex(sdl_initialized_mutex);
}

static int initialize_deferred_state()
Expand Down

0 comments on commit 6d60630

Please sign in to comment.