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