4 This file is part of PulseAudio.
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.
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 License
17 along with PulseAudio; if not, write to the Free Software
18 Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
29 #define AO_REQUIRE_CAS
30 #include <atomic_ops.h>
32 #include <pulse/xmalloc.h>
36 #define ASSERT_SUCCESS(x) do { \
43 pa_thread_func_t thread_func
;
52 static pa_tls
*thread_tls
;
53 static pthread_once_t thread_tls_once
= PTHREAD_ONCE_INIT
;
55 static void thread_tls_once_func(void) {
56 thread_tls
= pa_tls_new(NULL
);
60 static void* internal_thread_func(void *userdata
) {
61 pa_thread
*t
= userdata
;
64 t
->id
= pthread_self();
66 ASSERT_SUCCESS(pthread_once(&thread_tls_once
, thread_tls_once_func
));
67 pa_tls_set(thread_tls
, t
);
69 AO_store_release_write(&t
->running
, 1);
70 t
->thread_func(t
->userdata
);
71 AO_store_release_write(&t
->running
, 0);
76 pa_thread
* pa_thread_new(pa_thread_func_t thread_func
, void *userdata
) {
79 t
= pa_xnew(pa_thread
, 1);
80 t
->thread_func
= thread_func
;
81 t
->userdata
= userdata
;
83 if (pthread_create(&t
->id
, NULL
, internal_thread_func
, t
) < 0) {
91 int pa_thread_is_running(pa_thread
*t
) {
94 return !!AO_load_acquire_read(&t
->running
);
97 void pa_thread_free(pa_thread
*t
) {
104 int pa_thread_join(pa_thread
*t
) {
107 return pthread_join(t
->id
, NULL
);
110 pa_thread
* pa_thread_self(void) {
111 ASSERT_SUCCESS(pthread_once(&thread_tls_once
, thread_tls_once_func
));
112 return pa_tls_get(thread_tls
);
115 pa_tls
* pa_tls_new(pa_free_cb_t free_cb
) {
118 t
= pa_xnew(pa_tls
, 1);
120 if (pthread_key_create(&t
->key
, free_cb
) < 0) {
128 void pa_tls_free(pa_tls
*t
) {
131 ASSERT_SUCCESS(pthread_key_delete(t
->key
));
135 void *pa_tls_get(pa_tls
*t
) {
138 return pthread_getspecific(t
->key
);
141 void *pa_tls_set(pa_tls
*t
, void *userdata
) {
144 r
= pthread_getspecific(t
->key
);
145 ASSERT_SUCCESS(pthread_setspecific(t
->key
, userdata
));