Improved condition variable documentation
authorSam Lantinga <slouken@libsdl.org>
Thu, 27 Jan 2011 10:40:17 -0800
changeset 51100846f18eb625
parent 5109 5df0c142db9b
child 5111 481dabb098ef
Improved condition variable documentation
include/SDL_mutex.h
src/thread/generic/SDL_syscond.c
     1.1 --- a/include/SDL_mutex.h	Thu Jan 27 10:07:14 2011 -0800
     1.2 +++ b/include/SDL_mutex.h	Thu Jan 27 10:40:17 2011 -0800
     1.3 @@ -164,6 +164,31 @@
     1.4  
     1.5  /**
     1.6   *  Create a condition variable.
     1.7 + *
     1.8 + *  Typical use of condition variables:
     1.9 + *
    1.10 + *  Thread A:
    1.11 + *    SDL_LockMutex(lock);
    1.12 + *    while ( ! condition ) {
    1.13 + *        SDL_CondWait(cond, lock);
    1.14 + *    }
    1.15 + *    SDL_UnlockMutex(lock);
    1.16 + *
    1.17 + *  Thread B:
    1.18 + *    SDL_LockMutex(lock);
    1.19 + *    ...
    1.20 + *    condition = true;
    1.21 + *    ...
    1.22 + *    SDL_CondSignal(cond);
    1.23 + *    SDL_UnlockMutex(lock);
    1.24 + *
    1.25 + *  There is some discussion whether to signal the condition variable
    1.26 + *  with the mutex locked or not.  There is some potential performance
    1.27 + *  benefit to unlocking first on some platforms, but there are some
    1.28 + *  potential race conditions depending on how your code is structured.
    1.29 + *
    1.30 + *  In general it's safer to signal the condition variable while the
    1.31 + *  mutex is locked.
    1.32   */
    1.33  extern DECLSPEC SDL_cond *SDLCALL SDL_CreateCond(void);
    1.34  
    1.35 @@ -181,6 +206,7 @@
    1.36  
    1.37  /**
    1.38   *  Restart all threads that are waiting on the condition variable.
    1.39 + *
    1.40   *  \return 0 or -1 on error.
    1.41   */
    1.42  extern DECLSPEC int SDLCALL SDL_CondBroadcast(SDL_cond * cond);
     2.1 --- a/src/thread/generic/SDL_syscond.c	Thu Jan 27 10:07:14 2011 -0800
     2.2 +++ b/src/thread/generic/SDL_syscond.c	Thu Jan 27 10:40:17 2011 -0800
     2.3 @@ -145,18 +145,19 @@
     2.4  Typical use:
     2.5  
     2.6  Thread A:
     2.7 -	SDL_LockMutex(lock);
     2.8 -	while ( ! condition ) {
     2.9 -		SDL_CondWait(cond);
    2.10 -	}
    2.11 -	SDL_UnlockMutex(lock);
    2.12 +    SDL_LockMutex(lock);
    2.13 +    while ( ! condition ) {
    2.14 +        SDL_CondWait(cond, lock);
    2.15 +    }
    2.16 +    SDL_UnlockMutex(lock);
    2.17  
    2.18  Thread B:
    2.19 -	SDL_LockMutex(lock);
    2.20 -	...
    2.21 -	condition = true;
    2.22 -	...
    2.23 -	SDL_UnlockMutex(lock);
    2.24 +    SDL_LockMutex(lock);
    2.25 +    ...
    2.26 +    condition = true;
    2.27 +    ...
    2.28 +    SDL_CondSignal(cond);
    2.29 +    SDL_UnlockMutex(lock);
    2.30   */
    2.31  int
    2.32  SDL_CondWaitTimeout(SDL_cond * cond, SDL_mutex * mutex, Uint32 ms)