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"
26 #include "SDL_thread.h"
28 #if !SDL_THREAD_PTHREAD_RECURSIVE_MUTEX && \
29 !SDL_THREAD_PTHREAD_RECURSIVE_MUTEX_NP
30 #define FAKE_RECURSIVE_MUTEX
35 #if FAKE_RECURSIVE_MUTEX
41 SDL_mutex *SDL_CreateMutex (void)
44 pthread_mutexattr_t attr;
46 /* Allocate the structure */
47 mutex = (SDL_mutex *)SDL_calloc(1, sizeof(*mutex));
49 pthread_mutexattr_init(&attr);
50 #if SDL_THREAD_PTHREAD_RECURSIVE_MUTEX
51 pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE);
52 #elif SDL_THREAD_PTHREAD_RECURSIVE_MUTEX_NP
53 pthread_mutexattr_setkind_np(&attr, PTHREAD_MUTEX_RECURSIVE_NP);
55 /* No extra attributes necessary */
57 if ( pthread_mutex_init(&mutex->id, &attr) != 0 ) {
58 SDL_SetError("pthread_mutex_init() failed");
68 void SDL_DestroyMutex(SDL_mutex *mutex)
71 pthread_mutex_destroy(&mutex->id);
77 int SDL_mutexP(SDL_mutex *mutex)
80 #if FAKE_RECURSIVE_MUTEX
81 pthread_t this_thread;
84 if ( mutex == NULL ) {
85 SDL_SetError("Passed a NULL mutex");
90 #if FAKE_RECURSIVE_MUTEX
91 this_thread = pthread_self();
92 if ( mutex->owner == this_thread ) {
95 /* The order of operations is important.
96 We set the locking thread id after we obtain the lock
97 so unlocks from other threads will fail.
99 if ( pthread_mutex_lock(&mutex->id) == 0 ) {
100 mutex->owner = this_thread;
101 mutex->recursive = 0;
103 SDL_SetError("pthread_mutex_lock() failed");
108 if ( pthread_mutex_lock(&mutex->id) < 0 ) {
109 SDL_SetError("pthread_mutex_lock() failed");
116 int SDL_mutexV(SDL_mutex *mutex)
120 if ( mutex == NULL ) {
121 SDL_SetError("Passed a NULL mutex");
126 #if FAKE_RECURSIVE_MUTEX
127 /* We can only unlock the mutex if we own it */
128 if ( pthread_self() == mutex->owner ) {
129 if ( mutex->recursive ) {
132 /* The order of operations is important.
133 First reset the owner so another thread doesn't lock
134 the mutex and set the ownership before we reset it,
135 then release the lock semaphore.
138 pthread_mutex_unlock(&mutex->id);
141 SDL_SetError("mutex not owned by this thread");
146 if ( pthread_mutex_unlock(&mutex->id) < 0 ) {
147 SDL_SetError("pthread_mutex_unlock() failed");
150 #endif /* FAKE_RECURSIVE_MUTEX */