1 /*-*- Mode: C; c-basic-offset: 8 -*-*/
2 
3 /***
4   This file is part of libcanberra.
5 
6   Copyright 2008 Lennart Poettering
7 
8   libcanberra is free software; you can redistribute it and/or modify
9   it under the terms of the GNU Lesser General Public License as
10   published by the Free Software Foundation, either version 2.1 of the
11   License, or (at your option) any later version.
12 
13   libcanberra 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   Lesser General Public License for more details.
17 
18   You should have received a copy of the GNU Lesser General Public
19   License along with libcanberra. If not, see
20   <http://www.gnu.org/licenses/>.
21 ***/
22 
23 #ifdef HAVE_CONFIG_H
24 #include <config.h>
25 #endif
26 
27 #include <pthread.h>
28 #include <errno.h>
29 
30 #include "mutex.h"
31 #include "malloc.h"
32 
33 struct ca_mutex {
34         pthread_mutex_t mutex;
35 };
36 
ca_mutex_new(void)37 ca_mutex* ca_mutex_new(void) {
38         ca_mutex *m;
39 
40         if (!(m = ca_new(ca_mutex, 1)))
41                 return NULL;
42 
43         if (pthread_mutex_init(&m->mutex, NULL) < 0) {
44                 ca_free(m);
45                 return NULL;
46         }
47 
48         return m;
49 }
50 
ca_mutex_free(ca_mutex * m)51 void ca_mutex_free(ca_mutex *m) {
52         ca_assert(m);
53 
54         ca_assert_se(pthread_mutex_destroy(&m->mutex) == 0);
55         ca_free(m);
56 }
57 
ca_mutex_lock(ca_mutex * m)58 void ca_mutex_lock(ca_mutex *m) {
59         ca_assert(m);
60 
61         ca_assert_se(pthread_mutex_lock(&m->mutex) == 0);
62 }
63 
ca_mutex_try_lock(ca_mutex * m)64 ca_bool_t ca_mutex_try_lock(ca_mutex *m) {
65         int r;
66         ca_assert(m);
67 
68         if ((r = pthread_mutex_trylock(&m->mutex)) != 0) {
69                 ca_assert(r == EBUSY);
70                 return FALSE;
71         }
72 
73         return TRUE;
74 }
75 
ca_mutex_unlock(ca_mutex * m)76 void ca_mutex_unlock(ca_mutex *m) {
77         ca_assert(m);
78 
79         ca_assert_se(pthread_mutex_unlock(&m->mutex) == 0);
80 }
81