1 /***
2 This file is part of PulseAudio.
3
4 Copyright 2006 Lennart Poettering
5 Copyright 2013 Albert Zeyer
6
7 PulseAudio is free software; you can redistribute it and/or modify
8 it under the terms of the GNU Lesser General Public License as published
9 by the Free Software Foundation; either version 2.1 of the License,
10 or (at your option) any later version.
11
12 PulseAudio is distributed in the hope that it will be useful, but
13 WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 General Public License for more details.
16
17 You should have received a copy of the GNU Lesser General Public License
18 along with PulseAudio; if not, see <http://www.gnu.org/licenses/>.
19 ***/
20
21 #ifdef HAVE_CONFIG_H
22 #include <config.h>
23 #endif
24
25 #include <stdio.h>
26 #include <errno.h>
27 #include <pthread.h>
28 #include <semaphore.h>
29 #include <sys/types.h>
30 #include <unistd.h>
31
32 #include <pulse/xmalloc.h>
33 #include <pulsecore/macro.h>
34 #include <pulsecore/atomic.h>
35 #include <pulsecore/core-util.h>
36
37 #include "semaphore.h"
38
39 /* OSX doesn't support unnamed semaphores (via sem_init).
40 * Thus, we use a counter to give them enumerated names. */
41 static pa_atomic_t id_counter = PA_ATOMIC_INIT(0);
42
43 struct pa_semaphore {
44 sem_t *sem;
45 int id;
46 };
47
sem_name(char * fn,size_t l,int id)48 static char *sem_name(char *fn, size_t l, int id) {
49 pa_snprintf(fn, l, "/pulse-sem-%u-%u", getpid(), id);
50 return fn;
51 }
52
pa_semaphore_new(unsigned value)53 pa_semaphore *pa_semaphore_new(unsigned value) {
54 pa_semaphore *s;
55 char fn[32];
56
57 s = pa_xnew(pa_semaphore, 1);
58 s->id = pa_atomic_inc(&id_counter);
59 sem_name(fn, sizeof(fn), s->id);
60 sem_unlink(fn); /* in case an old stale semaphore is left around */
61 pa_assert_se(s->sem = sem_open(fn, O_CREAT|O_EXCL, 0700, value));
62 pa_assert(s->sem != SEM_FAILED);
63 return s;
64 }
65
pa_semaphore_free(pa_semaphore * s)66 void pa_semaphore_free(pa_semaphore *s) {
67 char fn[32];
68
69 pa_assert(s);
70
71 pa_assert_se(sem_close(s->sem) == 0);
72 sem_name(fn, sizeof(fn), s->id);
73 pa_assert_se(sem_unlink(fn) == 0);
74 pa_xfree(s);
75 }
76
pa_semaphore_post(pa_semaphore * s)77 void pa_semaphore_post(pa_semaphore *s) {
78 pa_assert(s);
79 pa_assert_se(sem_post(s->sem) == 0);
80 }
81
pa_semaphore_wait(pa_semaphore * s)82 void pa_semaphore_wait(pa_semaphore *s) {
83 int ret;
84
85 pa_assert(s);
86
87 do {
88 ret = sem_wait(s->sem);
89 } while (ret < 0 && errno == EINTR);
90
91 pa_assert(ret == 0);
92 }
93