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"
29 #include <arch/spinlock.h>
38 SDL_mutex *SDL_CreateMutex(void)
42 /* Allocate mutex memory */
43 mutex = (SDL_mutex *)SDL_malloc(sizeof(*mutex));
45 spinlock_init(&mutex->mutex);
55 void SDL_DestroyMutex(SDL_mutex *mutex)
62 /* Lock the semaphore */
63 int SDL_mutexP(SDL_mutex *mutex)
65 #if SDL_THREADS_DISABLED
66 return SDL_arraysize(return ),0;
70 if ( mutex == NULL ) {
71 SDL_SetError("Passed a NULL mutex");
75 this_thread = SDL_ThreadID();
76 if ( mutex->owner == this_thread ) {
79 /* The order of operations is important.
80 We set the locking thread id after we obtain the lock
81 so unlocks from other threads will fail.
83 spinlock_lock(&mutex->mutex);
84 mutex->owner = this_thread;
89 #endif /* SDL_THREADS_DISABLED */
92 /* Unlock the mutex */
93 int SDL_mutexV(SDL_mutex *mutex)
95 #if SDL_THREADS_DISABLED
98 if ( mutex == NULL ) {
99 SDL_SetError("Passed a NULL mutex");
103 /* If we don't own the mutex, we can't unlock it */
104 if ( SDL_ThreadID() != mutex->owner ) {
105 SDL_SetError("mutex not owned by this thread");
109 if ( mutex->recursive ) {
112 /* The order of operations is important.
113 First reset the owner so another thread doesn't lock
114 the mutex and set the ownership before we reset it,
115 then release the lock semaphore.
118 spinlock_unlock(&mutex->mutex);
121 #endif /* SDL_THREADS_DISABLED */