add a test program for the free list
[platform/upstream/pulseaudio.git] / 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/xmalloc.h>
31 #include <pulsecore/flist.h>
32 #include <pulsecore/thread.h>
33 #include <pulsecore/log.h>
34 #include <pulsecore/core-util.h>
35
36 #define THREADS_MAX 20
37
38 static pa_flist *flist;
39 static int quit = 0;
40
41 static void spin(void) {
42     int k;
43     
44     /* Spin a little */
45     k = rand() % 10000;
46     for (; k > 0; k--)
47         pa_thread_yield();
48 }
49
50 static void thread_func(void *data) {
51     char *s = data;
52     int n = 0;
53     int b = 1;
54
55     while (!quit) {
56         char *text, *t;
57
58         /* Allocate some memory, if possible take it from the flist */
59         if (b && (text = pa_flist_pop(flist)))
60             pa_log("%s: popped '%s'", s, text);
61         else {
62             text = pa_sprintf_malloc("Block %i, allocated by %s", n++, s);
63             pa_log("%s: allocated '%s'", s, text);
64         }
65
66         b = !b;
67
68         spin();
69
70         /* Give it back to the flist if possible */
71         if (pa_flist_push(flist, text) < 0) {
72             pa_log("%s: failed to push back '%s'", s, text);
73             pa_xfree(text);
74         } else
75             pa_log("%s: pushed", s);
76
77         spin();
78     }
79
80     if (pa_flist_push(flist, s) < 0)
81         pa_xfree(s);
82 }
83
84 int main(int argc, char* argv[]) {
85     pa_thread *threads[THREADS_MAX];
86     int i;
87
88     flist = pa_flist_new(0);
89
90     for (i = 0; i < THREADS_MAX; i++) {
91         threads[i] = pa_thread_new(thread_func, pa_sprintf_malloc("Thread #%i", i+1));
92         assert(threads[i]);
93     }
94
95     sleep(60);
96     quit = 1;
97
98     for (i = 0; i < THREADS_MAX; i++)
99         pa_thread_free(threads[i]);
100
101     pa_flist_free(flist, pa_xfree);
102     
103     return 0;
104 }