2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2009 Sam Lantinga
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Lesser General Public
7 License as published by the Free Software Foundation; either
8 version 2.1 of the License, or (at your option) any later version.
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Lesser General Public License for more details.
15 You should have received a copy of the GNU Lesser General Public
16 License along with this library; if not, write to the Free Software
17 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
22 #include "SDL_config.h"
24 /* An implementation of mutexes using semaphores */
26 #include "SDL_thread.h"
27 #include "SDL_systhread_c.h"
37 SDL_mutex *SDL_CreateMutex(void)
41 /* Allocate mutex memory */
42 mutex = (SDL_mutex *)SDL_malloc(sizeof(*mutex));
44 /* Create the mutex semaphore, with initial value 1 */
45 mutex->sem = SDL_CreateSemaphore(1);
59 void SDL_DestroyMutex(SDL_mutex *mutex)
63 SDL_DestroySemaphore(mutex->sem);
69 /* Lock the semaphore */
70 int SDL_mutexP(SDL_mutex *mutex)
72 #if SDL_THREADS_DISABLED
77 if ( mutex == NULL ) {
78 SDL_SetError("Passed a NULL mutex");
82 this_thread = SDL_ThreadID();
83 if ( mutex->owner == this_thread ) {
86 /* The order of operations is important.
87 We set the locking thread id after we obtain the lock
88 so unlocks from other threads will fail.
90 SDL_SemWait(mutex->sem);
91 mutex->owner = this_thread;
96 #endif /* SDL_THREADS_DISABLED */
99 /* Unlock the mutex */
100 int SDL_mutexV(SDL_mutex *mutex)
102 #if SDL_THREADS_DISABLED
105 if ( mutex == NULL ) {
106 SDL_SetError("Passed a NULL mutex");
110 /* If we don't own the mutex, we can't unlock it */
111 if ( SDL_ThreadID() != mutex->owner ) {
112 SDL_SetError("mutex not owned by this thread");
116 if ( mutex->recursive ) {
119 /* The order of operations is important.
120 First reset the owner so another thread doesn't lock
121 the mutex and set the ownership before we reset it,
122 then release the lock semaphore.
125 SDL_SemPost(mutex->sem);
128 #endif /* SDL_THREADS_DISABLED */