Expose mutex assertions

Add a function to assert that the mutex is held (or not).
This commit is contained in:
Romain Vimont 2021-01-31 18:55:03 +01:00
parent d2689fc168
commit 21d206f360
2 changed files with 30 additions and 0 deletions

View file

@ -30,6 +30,9 @@ sc_mutex_init(sc_mutex *mutex) {
} }
mutex->mutex = sdl_mutex; mutex->mutex = sdl_mutex;
#ifndef NDEBUG
mutex->locker = 0;
#endif
return true; return true;
} }
@ -46,6 +49,8 @@ sc_mutex_lock(sc_mutex *mutex) {
LOGC("Could not lock mutex: %s", SDL_GetError()); LOGC("Could not lock mutex: %s", SDL_GetError());
abort(); abort();
} }
mutex->locker = sc_thread_get_id();
#else #else
(void) r; (void) r;
#endif #endif
@ -53,6 +58,9 @@ sc_mutex_lock(sc_mutex *mutex) {
void void
sc_mutex_unlock(sc_mutex *mutex) { sc_mutex_unlock(sc_mutex *mutex) {
#ifndef NDEBUG
mutex->locker = 0;
#endif
int r = SDL_UnlockMutex(mutex->mutex); int r = SDL_UnlockMutex(mutex->mutex);
#ifndef NDEBUG #ifndef NDEBUG
if (r) { if (r) {
@ -69,6 +77,13 @@ sc_thread_get_id(void) {
return SDL_ThreadID(); return SDL_ThreadID();
} }
#ifndef NDEBUG
bool
sc_mutex_held(struct sc_mutex *mutex) {
return mutex->locker == sc_thread_get_id();
}
#endif
bool bool
sc_cond_init(sc_cond *cond) { sc_cond_init(sc_cond *cond) {
SDL_cond *sdl_cond = SDL_CreateCond(); SDL_cond *sdl_cond = SDL_CreateCond();
@ -93,6 +108,8 @@ sc_cond_wait(sc_cond *cond, sc_mutex *mutex) {
LOGC("Could not wait on condition: %s", SDL_GetError()); LOGC("Could not wait on condition: %s", SDL_GetError());
abort(); abort();
} }
mutex->locker = sc_thread_get_id();
#else #else
(void) r; (void) r;
#endif #endif
@ -106,6 +123,8 @@ sc_cond_timedwait(sc_cond *cond, sc_mutex *mutex, uint32_t ms) {
LOGC("Could not wait on condition with timeout: %s", SDL_GetError()); LOGC("Could not wait on condition with timeout: %s", SDL_GetError());
abort(); abort();
} }
mutex->locker = sc_thread_get_id();
#endif #endif
assert(r == 0 || r == SDL_MUTEX_TIMEDOUT); assert(r == 0 || r == SDL_MUTEX_TIMEDOUT);
return r == 0; return r == 0;

View file

@ -20,6 +20,9 @@ typedef struct sc_thread {
typedef struct sc_mutex { typedef struct sc_mutex {
SDL_mutex *mutex; SDL_mutex *mutex;
#ifndef NDEBUG
sc_thread_id locker;
#endif
} sc_mutex; } sc_mutex;
typedef struct sc_cond { typedef struct sc_cond {
@ -48,6 +51,14 @@ sc_mutex_unlock(sc_mutex *mutex);
sc_thread_id sc_thread_id
sc_thread_get_id(void); sc_thread_get_id(void);
#ifndef NDEBUG
bool
sc_mutex_held(struct sc_mutex *mutex);
# define sc_mutex_assert(mutex) assert(sc_mutex_held(mutex))
#else
# define sc_mutex_assert(mutex)
#endif
bool bool
sc_cond_init(sc_cond *cond); sc_cond_init(sc_cond *cond);