Merge HUGE set of changes temporarily into a branch, to allow me to move them from...
[profile/ivi/pulseaudio-panda.git] / src / pulsecore / once-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 <pulsecore/macro.h>
31 #include <pulsecore/mutex.h>
32
33 #include "once.h"
34
35 /* Not reentrant -- how could it be? */
36 void pa_once(pa_once_t *control, pa_once_func_t func) {
37     pa_mutex *m;
38     
39     pa_assert(control);
40     pa_assert(func);
41
42     if (pa_atomic_load(&control->done))
43         return;
44     
45     pa_atomic_inc(&control->ref);
46         
47     for (;;) {
48         
49         if ((m = pa_atomic_ptr_load(&control->mutex))) {
50
51             /* The mutex is stored in locked state, hence let's just
52              * wait until it is unlocked */
53             pa_mutex_lock(m);
54             pa_mutex_unlock(m);
55             break;
56         }
57
58         pa_assert_se(m = pa_mutex_new(0));
59         pa_mutex_lock(m);
60         
61         if (pa_atomic_ptr_cmpxchg(&control->mutex, NULL, m)) {
62             func();
63             pa_atomic_store(&control->done, 1);
64             pa_mutex_unlock(m);
65
66             break;
67         }
68
69         pa_mutex_unlock(m);
70         pa_mutex_free(m);
71     }
72
73     pa_assert(pa_atomic_load(&control->done));
74     
75     if (pa_atomic_dec(&control->ref) <= 1) {
76         pa_assert(pa_atomic_ptr_cmpxchg(&control->mutex, m, NULL));
77         pa_mutex_free(m);
78     }
79
80     /* Caveat: We have to make sure that the once func has completed
81      * before returning, even if the once func is not actually
82      * executed by us. Hence the awkward locking. */
83 }