]> code.delx.au - pulseaudio/blob - src/tests/once-test.c
5b55532c41b0d83645036f1ef68646a5a7e9c2b5
[pulseaudio] / src / tests / once-test.c
1 /***
2 This file is part of PulseAudio.
3
4 PulseAudio is free software; you can redistribute it and/or modify
5 it under the terms of the GNU Lesser General Public License as published
6 by the Free Software Foundation; either version 2.1 of the License,
7 or (at your option) any later version.
8
9 PulseAudio is distributed in the hope that it will be useful, but
10 WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
12 General Public License for more details.
13
14 You should have received a copy of the GNU Lesser General Public License
15 along with PulseAudio; if not, write to the Free Software
16 Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
17 USA.
18 ***/
19
20 #ifdef HAVE_CONFIG_H
21 #include <config.h>
22 #endif
23
24 #include <pthread.h>
25
26 #include <pulsecore/thread.h>
27 #include <pulsecore/mutex.h>
28 #include <pulsecore/once.h>
29 #include <pulsecore/log.h>
30 #include <pulsecore/core-util.h>
31 #include <pulsecore/core-error.h>
32 #include <pulsecore/atomic.h>
33 #include <pulse/xmalloc.h>
34
35 static pa_once once = PA_ONCE_INIT;
36 static volatile unsigned n_run = 0;
37 static const char * volatile ran_by = NULL;
38 static pthread_barrier_t barrier;
39 static pa_atomic_t i_cpu = PA_ATOMIC_INIT(0);
40 static unsigned n_cpu;
41
42 #define N_ITERATIONS 500
43 #define N_THREADS 100
44
45 static void once_func(void) {
46 n_run++;
47 ran_by = (const char*) pa_thread_get_data(pa_thread_self());
48 }
49
50 static void thread_func(void *data) {
51 int r;
52
53 #ifdef HAVE_PTHREAD_SETAFFINITY_NP
54 cpu_set_t mask;
55
56 CPU_ZERO(&mask);
57 CPU_SET((size_t) (pa_atomic_inc(&i_cpu) % n_cpu), &mask);
58 pa_assert_se(pthread_setaffinity_np(pthread_self(), sizeof(mask), &mask) == 0);
59 #endif
60
61 /* pa_log("started up: %s", data); */
62
63 r = pthread_barrier_wait(&barrier);
64 pa_assert(r == 0 || r == PTHREAD_BARRIER_SERIAL_THREAD);
65
66 pa_run_once(&once, once_func);
67 }
68
69 int main(int argc, char *argv[]) {
70 unsigned n, i;
71
72 n_cpu = pa_ncpus();
73
74 for (n = 0; n < N_ITERATIONS; n++) {
75 pa_thread* threads[N_THREADS];
76
77 pa_assert_se(pthread_barrier_init(&barrier, NULL, N_THREADS) == 0);
78
79 /* Yes, kinda ugly */
80 pa_zero(once);
81
82 for (i = 0; i < N_THREADS; i++)
83 threads[i] = pa_thread_new(thread_func, pa_sprintf_malloc("Thread #%i", i+1));
84
85 for (i = 0; i < N_THREADS; i++)
86 pa_thread_join(threads[i]);
87
88 pa_assert(n_run == 1);
89 pa_log("ran by %s", ran_by);
90
91 for (i = 0; i < N_THREADS; i++) {
92 pa_xfree(pa_thread_get_data(threads[i]));
93 pa_thread_free(threads[i]);
94 }
95
96 n_run = 0;
97 ran_by = NULL;
98
99 pa_assert_se(pthread_barrier_destroy(&barrier) == 0);
100 }
101
102 return 0;
103 }