2 This file is part of PulseAudio.
4 Copyright 2009 Lennart Poettering
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
8 published by the Free Software Foundation; either version 2.1 of the
9 License, or (at your option) any later version.
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.
16 You should have received a copy of the GNU Lesser General Public
17 License along with PulseAudio; if not, write to the Free Software
18 Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
26 #include <pulse/xmalloc.h>
28 #include <pulsecore/semaphore.h>
29 #include <pulsecore/macro.h>
30 #include <pulsecore/mutex.h>
34 #define MSB (1U << (sizeof(unsigned)*8U-1))
35 #define WHICH(n) (!!((n) & MSB))
36 #define COUNTER(n) ((n) & ~MSB)
39 pa_atomic_t read_lock
;
41 pa_semaphore
*semaphore
;
45 pa_aupdate
*pa_aupdate_new(void) {
48 a
= pa_xnew(pa_aupdate
, 1);
49 pa_atomic_store(&a
->read_lock
, 0);
50 a
->write_lock
= pa_mutex_new(FALSE
, FALSE
);
51 a
->semaphore
= pa_semaphore_new(0);
56 void pa_aupdate_free(pa_aupdate
*a
) {
59 pa_mutex_free(a
->write_lock
);
60 pa_semaphore_free(a
->semaphore
);
65 unsigned pa_aupdate_read_begin(pa_aupdate
*a
) {
70 /* Increase the lock counter */
71 n
= (unsigned) pa_atomic_inc(&a
->read_lock
);
73 /* When n is 0 we have about 2^31 threads running that all try to
74 * access the data at the same time, oh my! */
75 pa_assert(COUNTER(n
)+1 > 0);
77 /* The uppermost bit tells us which data to look at */
81 void pa_aupdate_read_end(pa_aupdate
*a
) {
86 /* Decrease the lock counter */
87 n
= (unsigned) pa_atomic_dec(&a
->read_lock
);
89 /* Make sure the counter was valid */
90 pa_assert(COUNTER(n
) > 0);
92 /* Post the semaphore */
93 pa_semaphore_post(a
->semaphore
);
96 unsigned pa_aupdate_write_begin(pa_aupdate
*a
) {
101 pa_mutex_lock(a
->write_lock
);
103 n
= (unsigned) pa_atomic_load(&a
->read_lock
);
110 unsigned pa_aupdate_write_swap(pa_aupdate
*a
) {
116 n
= (unsigned) pa_atomic_load(&a
->read_lock
);
118 /* If the read counter is > 0 wait; if it is 0 try to swap the lists */
120 pa_semaphore_wait(a
->semaphore
);
121 else if (pa_atomic_cmpxchg(&a
->read_lock
, (int) n
, (int) (n
^ MSB
)))
130 void pa_aupdate_write_end(pa_aupdate
*a
) {
134 pa_aupdate_write_swap(a
);
136 pa_mutex_unlock(a
->write_lock
);