2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997, 1998, 1999, 2000, 2001, 2002 Sam Lantinga
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Library General Public
7 License as published by the Free Software Foundation; either
8 version 2 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 Library General Public License for more details.
15 You should have received a copy of the GNU Library General Public
16 License along with this library; if not, write to the Free
17 Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
28 /* An implementation of semaphores using mutexes and condition variables */
30 #include "SDL_error.h"
31 #include "SDL_thread.h"
32 #include "SDL_systhread_c.h"
35 #include "SDL_timer.h"
41 struct SignalSemaphore Sem
;
44 SDL_mutex
*count_lock
;
45 SDL_cond
*count_nonzero
;
52 SDL_sem
*SDL_CreateSemaphore(Uint32 initial_value
)
56 sem
= (SDL_sem
*)malloc(sizeof(*sem
));
63 D(bug("Creating semaphore %lx...\n",sem
));
65 memset(sem
,0,sizeof(*sem
));
67 InitSemaphore(&sem
->Sem
);
72 void SDL_DestroySemaphore(SDL_sem
*sem
)
74 D(bug("Destroying semaphore %lx...\n",sem
));
77 // Condizioni per liberare i task in attesa?
82 int SDL_SemTryWait(SDL_sem
*sem
)
85 SDL_SetError("Passed a NULL semaphore");
89 D(bug("TryWait semaphore...%lx\n",sem
));
91 ObtainSemaphore(&sem
->Sem
);
92 // ReleaseSemaphore(&sem->Sem);
97 int SDL_SemWaitTimeout(SDL_sem
*sem
, Uint32 timeout
)
103 SDL_SetError("Passed a NULL semaphore");
107 D(bug("WaitTimeout (%ld) semaphore...%lx\n",timeout
,sem
));
109 /* A timeout of 0 is an easy case */
110 if ( timeout
== 0 ) {
111 return SDL_SemTryWait(sem
);
114 SDL_LockMutex(sem->count_lock);
115 ++sem->waiters_count;
117 while ( (sem->count == 0) && (retval != SDL_MUTEX_TIMEDOUT) ) {
118 retval = SDL_CondWaitTimeout(sem->count_nonzero,
119 sem->count_lock, timeout);
121 --sem->waiters_count;
123 SDL_UnlockMutex(sem->count_lock);
125 if(!(retval
=AttemptSemaphore(&sem
->Sem
)))
128 retval
=AttemptSemaphore(&sem
->Sem
);
133 // ReleaseSemaphore(&sem->Sem);
140 int SDL_SemWait(SDL_sem
*sem
)
142 ObtainSemaphore(&sem
->Sem
);
144 // return SDL_SemWaitTimeout(sem, SDL_MUTEX_MAXWAIT);
147 Uint32
SDL_SemValue(SDL_sem
*sem
)
154 value
= sem
->Sem
.ssppc_SS
.ss_NestCount
;
156 value
= sem
->Sem
.ss_NestCount
;
158 // SDL_UnlockMutex(sem->count_lock);
163 int SDL_SemPost(SDL_sem
*sem
)
166 SDL_SetError("Passed a NULL semaphore");
169 D(bug("SemPost semaphore...%lx\n",sem
));
171 ReleaseSemaphore(&sem
->Sem
);
173 SDL_LockMutex(sem
->count_lock
);
174 if ( sem
->waiters_count
> 0 ) {
175 SDL_CondSignal(sem
->count_nonzero
);
178 SDL_UnlockMutex(sem
->count_lock
);