Debian Codegraph @

libretro-common/rthreads/rsemaphore.c

raw symbols SCIP
1 /*
2 Copyright 2005 Allen B. Downey
3
4 This file contains an example program from The Little Book of
5 Semaphores, available from Green Tea Press, greenteapress.com
6
7 This program is free software; you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation; either version 2 of the License, or
10 (at your option) any later version.
11
12 This program is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 GNU General Public License for more details.
16
17 You should have received a copy of the GNU General Public License
18 along with this program; if not, see http://www.gnu.org/licenses/gpl.html
19 or write to the Free Software Foundation, Inc., 51 Franklin St,
20 Fifth Floor, Boston, MA 02110-1301 USA
21 */
22
23 /* Code taken from http://greenteapress.com/semaphores/semaphore.c
24 * and changed to use libretro-common's mutexes and conditions.
25 */
26
27 #include <stdlib.h>
28
29 #include <rthreads/rthreads.h>
30 #include <rthreads/rsemaphore.h>
31
32 struct ssem
33 {
34 int value;
35 int wakeups;
36 slock_t *mutex;
37 scond_t *cond;
38 };
39
40 ssem_t *ssem_new(int value)
41 {
42 ssem_t *semaphore = (ssem_t*)calloc(1, sizeof(*semaphore));
43
44 if (!semaphore)
45 goto error;
46
47 semaphore->value = value;
48 semaphore->wakeups = 0;
49 semaphore->mutex = slock_new();
50
51 if (!semaphore->mutex)
52 goto error;
53
54 semaphore->cond = scond_new();
55
56 if (!semaphore->cond)
57 goto error;
58
59 return semaphore;
60
61 error:
62 if (semaphore->mutex)
63 slock_free(semaphore->mutex);
64 semaphore->mutex = NULL;
65 if (semaphore)
66 free((void*)semaphore);
67 return NULL;
68 }
69
70 void ssem_free(ssem_t *semaphore)
71 {
72 if (!semaphore)
73 return;
74
75 scond_free(semaphore->cond);
76 slock_free(semaphore->mutex);
77 free((void*)semaphore);
78 }
79
80 void ssem_wait(ssem_t *semaphore)
81 {
82 if (!semaphore)
83 return;
84
85 slock_lock(semaphore->mutex);
86 semaphore->value--;
87
88 if (semaphore->value < 0)
89 {
90 do
91 {
92 scond_wait(semaphore->cond, semaphore->mutex);
93 }while (semaphore->wakeups < 1);
94
95 semaphore->wakeups--;
96 }
97
98 slock_unlock(semaphore->mutex);
99 }
100
101 void ssem_signal(ssem_t *semaphore)
102 {
103 if (!semaphore)
104 return;
105
106 slock_lock(semaphore->mutex);
107 semaphore->value++;
108
109 if (semaphore->value <= 0)
110 {
111 semaphore->wakeups++;
112 scond_signal(semaphore->cond);
113 }
114
115 slock_unlock(semaphore->mutex);
116 }