6f0e733659584c76b06b46584c4c0c2f60483643
[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         if (pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE) < 0)
56             return NULL;
57
58     m = pa_xnew(pa_mutex, 1);
59
60     if (pthread_mutex_init(&m->mutex, &attr) < 0) {
61         pa_xfree(m);
62         return NULL;
63     }
64
65     return m;
66 }
67
68 void pa_mutex_free(pa_mutex *m) {
69     assert(m);
70
71     ASSERT_SUCCESS(pthread_mutex_destroy(&m->mutex));
72     pa_xfree(m);
73 }
74
75 void pa_mutex_lock(pa_mutex *m) {
76     assert(m);
77
78     ASSERT_SUCCESS(pthread_mutex_lock(&m->mutex));
79 }
80
81 void pa_mutex_unlock(pa_mutex *m) {
82     assert(m);
83
84     ASSERT_SUCCESS(pthread_mutex_unlock(&m->mutex));
85 }
86
87
88 pa_cond *pa_cond_new(void) {
89     pa_cond *c;
90
91     c = pa_xnew(pa_cond, 1);
92
93     if (pthread_cond_init(&c->cond, NULL) < 0) {
94         pa_xfree(c);
95         return NULL;
96     }
97
98     return c;
99 }
100
101 void pa_cond_free(pa_cond *c) {
102     assert(c);
103
104     ASSERT_SUCCESS(pthread_cond_destroy(&c->cond));
105     pa_xfree(c);
106 }
107
108 void pa_cond_signal(pa_cond *c, int broadcast) {
109     assert(c);
110
111     if (broadcast)
112         ASSERT_SUCCESS(pthread_cond_broadcast(&c->cond));
113     else
114         ASSERT_SUCCESS(pthread_cond_signal(&c->cond));
115 }
116
117 int pa_cond_wait(pa_cond *c, pa_mutex *m) {
118     assert(c);
119     assert(m);
120
121     return pthread_cond_wait(&c->cond, &m->mutex);
122 }