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