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
28 #include <atomic_ops.h>
30 #include <pulse/xmalloc.h>
34 #define ASSERT_SUCCESS(x) do { \
41 pa_thread_func_t thread_func
;
50 static pa_tls
*thread_tls
;
51 static pthread_once_t thread_tls_once
= PTHREAD_ONCE_INIT
;
53 static void thread_tls_once_func(void) {
54 thread_tls
= pa_tls_new(NULL
);
58 static void* internal_thread_func(void *userdata
) {
59 pa_thread
*t
= userdata
;
62 t
->id
= pthread_self();
64 ASSERT_SUCCESS(pthread_once(&thread_tls_once
, thread_tls_once_func
));
65 pa_tls_set(thread_tls
, t
);
67 AO_store_release_write(&t
->running
, 1);
68 t
->thread_func(t
->userdata
);
69 AO_store_release_write(&t
->running
, 0);
74 pa_thread
* pa_thread_new(pa_thread_func_t thread_func
, void *userdata
) {
77 t
= pa_xnew(pa_thread
, 1);
78 t
->thread_func
= thread_func
;
79 t
->userdata
= userdata
;
81 if (pthread_create(&t
->id
, NULL
, internal_thread_func
, t
) < 0) {
89 int pa_thread_is_running(pa_thread
*t
) {
92 return !!AO_load_acquire_read(&t
->running
);
95 void pa_thread_free(pa_thread
*t
) {
102 int pa_thread_join(pa_thread
*t
) {
105 return pthread_join(t
->id
, NULL
);
108 pa_thread
* pa_thread_self(void) {
109 ASSERT_SUCCESS(pthread_once(&thread_tls_once
, thread_tls_once_func
));
110 return pa_tls_get(thread_tls
);
113 pa_tls
* pa_tls_new(pa_free_cb_t free_cb
) {
116 t
= pa_xnew(pa_tls
, 1);
118 if (pthread_key_create(&t
->key
, free_cb
) < 0) {
126 void pa_tls_free(pa_tls
*t
) {
129 ASSERT_SUCCESS(pthread_key_delete(t
->key
));
133 void *pa_tls_get(pa_tls
*t
) {
136 return pthread_getspecific(t
->key
);
139 void *pa_tls_set(pa_tls
*t
, void *userdata
) {
142 r
= pthread_getspecific(t
->key
);
143 ASSERT_SUCCESS(pthread_setspecific(t
->key
, userdata
));