From 101bb6f35f14681fc782078f65af65263c3ae7bc Mon Sep 17 00:00:00 2001 From: Sam Lantinga Date: Thu, 27 Jan 2011 10:40:17 -0800 Subject: [PATCH] Improved condition variable documentation --- include/SDL_mutex.h | 26 ++++++++++++++++++++++++++ src/thread/generic/SDL_syscond.c | 21 +++++++++++---------- 2 files changed, 37 insertions(+), 10 deletions(-) diff --git a/include/SDL_mutex.h b/include/SDL_mutex.h index e066f944b..c117bdbcc 100644 --- a/include/SDL_mutex.h +++ b/include/SDL_mutex.h @@ -164,6 +164,31 @@ typedef struct SDL_cond SDL_cond; /** * Create a condition variable. + * + * Typical use of condition variables: + * + * Thread A: + * SDL_LockMutex(lock); + * while ( ! condition ) { + * SDL_CondWait(cond, lock); + * } + * SDL_UnlockMutex(lock); + * + * Thread B: + * SDL_LockMutex(lock); + * ... + * condition = true; + * ... + * SDL_CondSignal(cond); + * SDL_UnlockMutex(lock); + * + * There is some discussion whether to signal the condition variable + * with the mutex locked or not. There is some potential performance + * benefit to unlocking first on some platforms, but there are some + * potential race conditions depending on how your code is structured. + * + * In general it's safer to signal the condition variable while the + * mutex is locked. */ extern DECLSPEC SDL_cond *SDLCALL SDL_CreateCond(void); @@ -181,6 +206,7 @@ extern DECLSPEC int SDLCALL SDL_CondSignal(SDL_cond * cond); /** * Restart all threads that are waiting on the condition variable. + * * \return 0 or -1 on error. */ extern DECLSPEC int SDLCALL SDL_CondBroadcast(SDL_cond * cond); diff --git a/src/thread/generic/SDL_syscond.c b/src/thread/generic/SDL_syscond.c index d2db76949..97383bef3 100644 --- a/src/thread/generic/SDL_syscond.c +++ b/src/thread/generic/SDL_syscond.c @@ -145,18 +145,19 @@ SDL_CondBroadcast(SDL_cond * cond) Typical use: Thread A: - SDL_LockMutex(lock); - while ( ! condition ) { - SDL_CondWait(cond); - } - SDL_UnlockMutex(lock); + SDL_LockMutex(lock); + while ( ! condition ) { + SDL_CondWait(cond, lock); + } + SDL_UnlockMutex(lock); Thread B: - SDL_LockMutex(lock); - ... - condition = true; - ... - SDL_UnlockMutex(lock); + SDL_LockMutex(lock); + ... + condition = true; + ... + SDL_CondSignal(cond); + SDL_UnlockMutex(lock); */ int SDL_CondWaitTimeout(SDL_cond * cond, SDL_mutex * mutex, Uint32 ms)