]> code.delx.au - pulseaudio/blob - src/tests/flist-test.c
rework memory block management to be thread-safe and mostly lock-free.
[pulseaudio] / src / tests / flist-test.c
1 /* $Id$ */
2
3 /***
4 This file is part of PulseAudio.
5
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.
10
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.
15
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
19 USA.
20 ***/
21
22 #ifdef HAVE_CONFIG_H
23 #include <config.h>
24 #endif
25
26 #include <assert.h>
27 #include <stdlib.h>
28 #include <unistd.h>
29
30 #include <pulse/util.h>
31 #include <pulse/xmalloc.h>
32 #include <pulsecore/flist.h>
33 #include <pulsecore/thread.h>
34 #include <pulsecore/log.h>
35 #include <pulsecore/core-util.h>
36
37 #define THREADS_MAX 20
38
39 static pa_flist *flist;
40 static int quit = 0;
41
42 static void spin(void) {
43 int k;
44
45 /* Spin a little */
46 k = rand() % 10000;
47 for (; k > 0; k--)
48 pa_thread_yield();
49 }
50
51 static void thread_func(void *data) {
52 char *s = data;
53 int n = 0;
54 int b = 1;
55
56 while (!quit) {
57 char *text;
58
59 /* Allocate some memory, if possible take it from the flist */
60 if (b && (text = pa_flist_pop(flist)))
61 pa_log("%s: popped '%s'", s, text);
62 else {
63 text = pa_sprintf_malloc("Block %i, allocated by %s", n++, s);
64 pa_log("%s: allocated '%s'", s, text);
65 }
66
67 b = !b;
68
69 spin();
70
71 /* Give it back to the flist if possible */
72 if (pa_flist_push(flist, text) < 0) {
73 pa_log("%s: failed to push back '%s'", s, text);
74 pa_xfree(text);
75 } else
76 pa_log("%s: pushed", s);
77
78 spin();
79 }
80
81 if (pa_flist_push(flist, s) < 0)
82 pa_xfree(s);
83 }
84
85 int main(int argc, char* argv[]) {
86 pa_thread *threads[THREADS_MAX];
87 int i;
88
89 flist = pa_flist_new(0);
90
91 for (i = 0; i < THREADS_MAX; i++) {
92 threads[i] = pa_thread_new(thread_func, pa_sprintf_malloc("Thread #%i", i+1));
93 assert(threads[i]);
94 }
95
96 pa_msleep(60000);
97 quit = 1;
98
99 for (i = 0; i < THREADS_MAX; i++)
100 pa_thread_free(threads[i]);
101
102 pa_flist_free(flist, pa_xfree);
103
104 return 0;
105 }