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"
25 #include <semaphore.h>
28 #include "SDL_thread.h"
29 #include "SDL_timer.h"
31 /* Wrapper around POSIX 1003.1b semaphores */
34 /* Mac OS X doesn't support sem_getvalue() as of version 10.4 */
35 #include "../generic/SDL_syssem.c"
38 struct SDL_semaphore {
42 /* Create a semaphore, initialized with value */
43 SDL_sem *SDL_CreateSemaphore(Uint32 initial_value)
45 SDL_sem *sem = (SDL_sem *) SDL_malloc(sizeof(SDL_sem));
47 if ( sem_init(&sem->sem, 0, initial_value) < 0 ) {
48 SDL_SetError("sem_init() failed");
58 void SDL_DestroySemaphore(SDL_sem *sem)
61 sem_destroy(&sem->sem);
66 int SDL_SemTryWait(SDL_sem *sem)
71 SDL_SetError("Passed a NULL semaphore");
74 retval = SDL_MUTEX_TIMEDOUT;
75 if ( sem_trywait(&sem->sem) == 0 ) {
81 int SDL_SemWait(SDL_sem *sem)
86 SDL_SetError("Passed a NULL semaphore");
90 while ( ((retval = sem_wait(&sem->sem)) == -1) && (errno == EINTR) ) {}
92 SDL_SetError("sem_wait() failed");
97 int SDL_SemWaitTimeout(SDL_sem *sem, Uint32 timeout)
102 SDL_SetError("Passed a NULL semaphore");
106 /* Try the easy cases first */
107 if ( timeout == 0 ) {
108 return SDL_SemTryWait(sem);
110 if ( timeout == SDL_MUTEX_MAXWAIT ) {
111 return SDL_SemWait(sem);
114 /* Ack! We have to busy wait... */
115 /* FIXME: Use sem_timedwait()? */
116 timeout += SDL_GetTicks();
118 retval = SDL_SemTryWait(sem);
123 } while ( SDL_GetTicks() < timeout );
128 Uint32 SDL_SemValue(SDL_sem *sem)
132 sem_getvalue(&sem->sem, &ret);
140 int SDL_SemPost(SDL_sem *sem)
145 SDL_SetError("Passed a NULL semaphore");
149 retval = sem_post(&sem->sem);
151 SDL_SetError("sem_post() failed");
156 #endif /* __MACOSX__ */