changeset 5112:0846f18eb625

Improved condition variable documentation
author Sam Lantinga <slouken@libsdl.org>
date Thu, 27 Jan 2011 10:40:17 -0800
parents 5df0c142db9b
children 481dabb098ef
files include/SDL_mutex.h src/thread/generic/SDL_syscond.c
diffstat 2 files changed, 37 insertions(+), 10 deletions(-) [+]
line wrap: on
line diff
--- a/include/SDL_mutex.h	Thu Jan 27 10:07:14 2011 -0800
+++ b/include/SDL_mutex.h	Thu Jan 27 10:40:17 2011 -0800
@@ -164,6 +164,31 @@
 
 /**
  *  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 @@
 
 /**
  *  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);
--- a/src/thread/generic/SDL_syscond.c	Thu Jan 27 10:07:14 2011 -0800
+++ b/src/thread/generic/SDL_syscond.c	Thu Jan 27 10:40:17 2011 -0800
@@ -145,18 +145,19 @@
 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)