make pa_mutex_new() and pa_cond_new() succeed in all cases. Similar behaviour to...
[profile/ivi/pulseaudio.git] / src / pulsecore / mutex-posix.c
1 /* $Id$ */
2
3 /***
4   This file is part of PulseAudio.
5  
6   PulseAudio is free software; you can redistribute it and/or modify
7   it under the terms of the GNU Lesser General Public License as published
8   by the Free Software Foundation; either version 2 of the License,
9   or (at your option) any later version.
10  
11   PulseAudio is distributed in the hope that it will be useful, but
12   WITHOUT ANY WARRANTY; without even the implied warranty of
13   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14   General Public License for more details.
15  
16   You should have received a copy of the GNU Lesser General Public License
17   along with PulseAudio; if not, write to the Free Software
18   Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
19   USA.
20 ***/
21
22 #ifdef HAVE_CONFIG_H
23 #include <config.h>
24 #endif
25
26 #include <assert.h>
27 #include <pthread.h>
28
29 #include <atomic_ops.h>
30
31 #include <pulse/xmalloc.h>
32
33 #include "mutex.h"
34
35 #define ASSERT_SUCCESS(x) do { \
36     int _r = (x); \
37     assert(_r == 0); \
38 } while(0)
39
40 struct pa_mutex {
41     pthread_mutex_t mutex;
42 };
43
44 struct pa_cond {
45     pthread_cond_t cond;
46 };
47
48 pa_mutex* pa_mutex_new(int recursive) {
49     pa_mutex *m;
50     pthread_mutexattr_t attr;
51
52     pthread_mutexattr_init(&attr);
53
54     if (recursive)
55         ASSERT_SUCCESS(pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE));
56
57     m = pa_xnew(pa_mutex, 1);
58
59     ASSERT_SUCCESS(pthread_mutex_init(&m->mutex, &attr));
60     return m;
61 }
62
63 void pa_mutex_free(pa_mutex *m) {
64     assert(m);
65
66     ASSERT_SUCCESS(pthread_mutex_destroy(&m->mutex));
67     pa_xfree(m);
68 }
69
70 void pa_mutex_lock(pa_mutex *m) {
71     assert(m);
72
73     ASSERT_SUCCESS(pthread_mutex_lock(&m->mutex));
74 }
75
76 void pa_mutex_unlock(pa_mutex *m) {
77     assert(m);
78
79     ASSERT_SUCCESS(pthread_mutex_unlock(&m->mutex));
80 }
81
82 pa_cond *pa_cond_new(void) {
83     pa_cond *c;
84
85     c = pa_xnew(pa_cond, 1);
86
87     ASSERT_SUCCESS(pthread_cond_init(&c->cond, NULL));
88     return c;
89 }
90
91 void pa_cond_free(pa_cond *c) {
92     assert(c);
93
94     ASSERT_SUCCESS(pthread_cond_destroy(&c->cond));
95     pa_xfree(c);
96 }
97
98 void pa_cond_signal(pa_cond *c, int broadcast) {
99     assert(c);
100
101     if (broadcast)
102         ASSERT_SUCCESS(pthread_cond_broadcast(&c->cond));
103     else
104         ASSERT_SUCCESS(pthread_cond_signal(&c->cond));
105 }
106
107 int pa_cond_wait(pa_cond *c, pa_mutex *m) {
108     assert(c);
109     assert(m);
110
111     return pthread_cond_wait(&c->cond, &m->mutex);
112 }