emscripten-ports / SDL2

Other
166 stars 64 forks source link

Fix mutex ownership in pthread SDL_CondWait() #131

Open baklazan opened 4 years ago

baklazan commented 4 years ago

This commit fixes a following bug in pthread versions of SDL_CondWait() and SDL_CondWaitTimeout():

When call to pthread_cond_wait() (or pthread_cond_timedwait()) succeeds and the current thread reacquires the pthread_mutex, it doesn't properly update its wrapper (the SDL_mutex object). If FAKE_RECURSIVE_MUTEX is set, this leads to problems in the following scenario:

SDL_mutex *mutex;
SDL_cond *cond;

Thread A:    
  SDL_LockMutex(mutex);
  SDL_CondWait(cond, mutex);
  SDL_UnlockMutex(mutex);
Thread B:
  SDL_LockMutex(mutex);
  SDL_UnlockMutex(mutex);
  SDL_CondSignal(cond);

Execution:
  Thread A: SDL_LockMutex(mutex);
  Thread A: SDL_CondWait(cond, mutex); // releases mutex and blocks
  Thread B: SDL_LockMutex(mutex);      // updates mutex->owner to Thread B
  Thread B: SDL_UnlockMutex(mutex);    // updates mutex->owner to 0
  Thread B: SDL_CondSignal(conde);     // unblocks Thread A
  Thread A: SDL_UnlockMutex(mutex);    // error: mutex not owned by this thread