8e11a3d3bdc4e9cc112f5c412672472a45c7d805
[platform/upstream/gstreamer.git] / gst / gstatomicqueue.c
1 /* GStreamer
2  * Copyright (C) 2009 Edward Hervey <bilboed@bilboed.com>
3  *               2011 Wim Taymans <wim.taymans@gmail.com>
4  *
5  * gstatomicqueue.c:
6  *
7  * This library is free software; you can redistribute it and/or
8  * modify it under the terms of the GNU Library General Public
9  * License as published by the Free Software Foundation; either
10  * version 2 of the License, or (at your option) any later version.
11  *
12  * This library is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15  * Library General Public License for more details.
16  *
17  * You should have received a copy of the GNU Library General Public
18  * License along with this library; if not, write to the
19  * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
20  * Boston, MA 02111-1307, USA.
21  */
22
23 #include "gst_private.h"
24
25 #include <string.h>
26
27 #include <gst/gst.h>
28 #include "gstatomicqueue.h"
29 #include "glib-compat-private.h"
30
31 /**
32  * SECTION:gstatomicqueue
33  * @title: GstAtomicQueue
34  * @short_description: An atomic queue implementation
35  *
36  * The #GstAtomicQueue object implements a queue that can be used from multiple
37  * threads without performing any blocking operations.
38  *
39  * Since: 0.10.33
40  */
41
42 G_DEFINE_BOXED_TYPE (GstAtomicQueue, gst_atomic_queue,
43     (GBoxedCopyFunc) gst_atomic_queue_ref,
44     (GBoxedFreeFunc) gst_atomic_queue_unref);
45
46 /* By default the queue uses 2 * sizeof(gpointer) * clp2 (max_items) of
47  * memory. clp2(x) is the next power of two >= than x.
48  *
49  * The queue can operate in low memory mode, in which it consumes almost
50  * half the memory at the expense of extra overhead in the readers. This
51  * is disabled by default because even without LOW_MEM mode, the memory
52  * consumption is still lower than a plain GList.
53  */
54 #undef LOW_MEM
55
56 typedef struct _GstAQueueMem GstAQueueMem;
57
58 struct _GstAQueueMem
59 {
60   gint size;
61   gpointer *array;
62   volatile gint head;
63   volatile gint tail_write;
64   volatile gint tail_read;
65   GstAQueueMem *next;
66   GstAQueueMem *free;
67 };
68
69 static guint
70 clp2 (guint n)
71 {
72   guint res = 1;
73
74   while (res < n)
75     res <<= 1;
76
77   return res;
78 }
79
80 static GstAQueueMem *
81 new_queue_mem (guint size, gint pos)
82 {
83   GstAQueueMem *mem;
84
85   mem = g_new (GstAQueueMem, 1);
86
87   /* we keep the size as a mask for performance */
88   mem->size = clp2 (MAX (size, 16)) - 1;
89   mem->array = g_new0 (gpointer, mem->size + 1);
90   mem->head = pos;
91   mem->tail_write = pos;
92   mem->tail_read = pos;
93   mem->next = NULL;
94   mem->free = NULL;
95
96   return mem;
97 }
98
99 static void
100 free_queue_mem (GstAQueueMem * mem)
101 {
102   g_free (mem->array);
103   g_free (mem);
104 }
105
106 struct _GstAtomicQueue
107 {
108   volatile gint refcount;
109 #ifdef LOW_MEM
110   gint num_readers;
111 #endif
112   GstAQueueMem *head_mem;
113   GstAQueueMem *tail_mem;
114   GstAQueueMem *free_list;
115 };
116
117 static void
118 add_to_free_list (GstAtomicQueue * queue, GstAQueueMem * mem)
119 {
120   do {
121     mem->free = g_atomic_pointer_get (&queue->free_list);
122   } while (!g_atomic_pointer_compare_and_exchange (&queue->free_list,
123           mem->free, mem));
124 }
125
126 static void
127 clear_free_list (GstAtomicQueue * queue)
128 {
129   GstAQueueMem *free_list;
130
131   /* take the free list and replace with NULL */
132   do {
133     free_list = g_atomic_pointer_get (&queue->free_list);
134     if (free_list == NULL)
135       return;
136   } while (!g_atomic_pointer_compare_and_exchange (&queue->free_list, free_list,
137           NULL));
138
139   while (free_list) {
140     GstAQueueMem *next = free_list->free;
141
142     free_queue_mem (free_list);
143
144     free_list = next;
145   }
146 }
147
148 /**
149  * gst_atomic_queue_new:
150  * @initial_size: initial queue size
151  *
152  * Create a new atomic queue instance. @initial_size will be rounded up to the
153  * nearest power of 2 and used as the initial size of the queue.
154  *
155  * Returns: a new #GstAtomicQueue
156  *
157  * Since: 0.10.33
158  */
159 GstAtomicQueue *
160 gst_atomic_queue_new (guint initial_size)
161 {
162   GstAtomicQueue *queue;
163
164   queue = g_new (GstAtomicQueue, 1);
165
166   queue->refcount = 1;
167 #ifdef LOW_MEM
168   queue->num_readers = 0;
169 #endif
170   queue->head_mem = queue->tail_mem = new_queue_mem (initial_size, 0);
171   queue->free_list = NULL;
172
173   return queue;
174 }
175
176 /**
177  * gst_atomic_queue_ref:
178  * @queue: a #GstAtomicQueue
179  *
180  * Increase the refcount of @queue.
181  *
182  * Since: 0.10.33
183  */
184 void
185 gst_atomic_queue_ref (GstAtomicQueue * queue)
186 {
187   g_return_if_fail (queue != NULL);
188
189   g_atomic_int_inc (&queue->refcount);
190 }
191
192 static void
193 gst_atomic_queue_free (GstAtomicQueue * queue)
194 {
195   free_queue_mem (queue->head_mem);
196   if (queue->head_mem != queue->tail_mem)
197     free_queue_mem (queue->tail_mem);
198   clear_free_list (queue);
199   g_free (queue);
200 }
201
202 /**
203  * gst_atomic_queue_unref:
204  * @queue: a #GstAtomicQueue
205  *
206  * Unref @queue and free the memory when the refcount reaches 0.
207  *
208  * Since: 0.10.33
209  */
210 void
211 gst_atomic_queue_unref (GstAtomicQueue * queue)
212 {
213   g_return_if_fail (queue != NULL);
214
215   if (g_atomic_int_dec_and_test (&queue->refcount))
216     gst_atomic_queue_free (queue);
217 }
218
219 /**
220  * gst_atomic_queue_peek:
221  * @queue: a #GstAtomicQueue
222  *
223  * Peek the head element of the queue without removing it from the queue.
224  *
225  * Returns: the head element of @queue or NULL when the queue is empty.
226  *
227  * Since: 0.10.33
228  */
229 gpointer
230 gst_atomic_queue_peek (GstAtomicQueue * queue)
231 {
232   GstAQueueMem *head_mem;
233   gint head, tail, size;
234
235   g_return_val_if_fail (queue != NULL, NULL);
236
237   while (TRUE) {
238     GstAQueueMem *next;
239
240     head_mem = g_atomic_pointer_get (&queue->head_mem);
241
242     head = g_atomic_int_get (&head_mem->head);
243     tail = g_atomic_int_get (&head_mem->tail_read);
244     size = head_mem->size;
245
246     /* when we are not empty, we can continue */
247     if (G_LIKELY (head != tail))
248       break;
249
250     /* else array empty, try to take next */
251     next = g_atomic_pointer_get (&head_mem->next);
252     if (next == NULL)
253       return NULL;
254
255     /* now we try to move the next array as the head memory. If we fail to do that,
256      * some other reader managed to do it first and we retry */
257     if (!g_atomic_pointer_compare_and_exchange (&queue->head_mem, head_mem,
258             next))
259       continue;
260
261     /* when we managed to swing the head pointer the old head is now
262      * useless and we add it to the freelist. We can't free the memory yet
263      * because we first need to make sure no reader is accessing it anymore. */
264     add_to_free_list (queue, head_mem);
265   }
266
267   return head_mem->array[head & size];
268 }
269
270 /**
271  * gst_atomic_queue_pop:
272  * @queue: a #GstAtomicQueue
273  *
274  * Get the head element of the queue.
275  *
276  * Returns: the head element of @queue or NULL when the queue is empty.
277  *
278  * Since: 0.10.33
279  */
280 gpointer
281 gst_atomic_queue_pop (GstAtomicQueue * queue)
282 {
283   gpointer ret;
284   GstAQueueMem *head_mem;
285   gint head, tail, size;
286
287   g_return_val_if_fail (queue != NULL, NULL);
288
289 #ifdef LOW_MEM
290   g_atomic_int_inc (&queue->num_readers);
291 #endif
292
293   do {
294     while (TRUE) {
295       GstAQueueMem *next;
296
297       head_mem = g_atomic_pointer_get (&queue->head_mem);
298
299       head = g_atomic_int_get (&head_mem->head);
300       tail = g_atomic_int_get (&head_mem->tail_read);
301       size = head_mem->size;
302
303       /* when we are not empty, we can continue */
304       if G_LIKELY
305         (head != tail)
306             break;
307
308       /* else array empty, try to take next */
309       next = g_atomic_pointer_get (&head_mem->next);
310       if (next == NULL)
311         return NULL;
312
313       /* now we try to move the next array as the head memory. If we fail to do that,
314        * some other reader managed to do it first and we retry */
315       if G_UNLIKELY
316         (!g_atomic_pointer_compare_and_exchange (&queue->head_mem, head_mem,
317                 next))
318             continue;
319
320       /* when we managed to swing the head pointer the old head is now
321        * useless and we add it to the freelist. We can't free the memory yet
322        * because we first need to make sure no reader is accessing it anymore. */
323       add_to_free_list (queue, head_mem);
324     }
325
326     ret = head_mem->array[head & size];
327   } while G_UNLIKELY
328   (!g_atomic_int_compare_and_exchange (&head_mem->head, head, head + 1));
329
330 #ifdef LOW_MEM
331   /* decrement number of readers, when we reach 0 readers we can be sure that
332    * none is accessing the memory in the free list and we can try to clean up */
333   if (g_atomic_int_dec_and_test (&queue->num_readers))
334     clear_free_list (queue);
335 #endif
336
337   return ret;
338 }
339
340 /**
341  * gst_atomic_queue_push:
342  * @queue: a #GstAtomicQueue
343  * @data: the data
344  *
345  * Append @data to the tail of the queue.
346  *
347  * Since: 0.10.33
348  */
349 void
350 gst_atomic_queue_push (GstAtomicQueue * queue, gpointer data)
351 {
352   GstAQueueMem *tail_mem;
353   gint head, tail, size;
354
355   g_return_if_fail (queue != NULL);
356
357   do {
358     while (TRUE) {
359       GstAQueueMem *mem;
360
361       tail_mem = g_atomic_pointer_get (&queue->tail_mem);
362       head = g_atomic_int_get (&tail_mem->head);
363       tail = g_atomic_int_get (&tail_mem->tail_write);
364       size = tail_mem->size;
365
366       /* we're not full, continue */
367       if G_LIKELY
368         (tail - head <= size)
369             break;
370
371       /* else we need to grow the array, we store a mask so we have to add 1 */
372       mem = new_queue_mem ((size << 1) + 1, tail);
373
374       /* try to make our new array visible to other writers */
375       if G_UNLIKELY
376         (!g_atomic_pointer_compare_and_exchange (&queue->tail_mem, tail_mem,
377                 mem)) {
378         /* we tried to swap the new writer array but something changed. This is
379          * because some other writer beat us to it, we free our memory and try
380          * again */
381         free_queue_mem (mem);
382         continue;
383         }
384       /* make sure that readers can find our new array as well. The one who
385        * manages to swap the pointer is the only one who can set the next
386        * pointer to the new array */
387       g_atomic_pointer_set (&tail_mem->next, mem);
388     }
389   } while G_UNLIKELY
390   (!g_atomic_int_compare_and_exchange (&tail_mem->tail_write, tail, tail + 1));
391
392   tail_mem->array[tail & size] = data;
393
394   /* now wait until all writers have completed their write before we move the
395    * tail_read to this new item. It is possible that other writers are still
396    * updating the previous array slots and we don't want to reveal their changes
397    * before they are done. FIXME, it would be nice if we didn't have to busy
398    * wait here. */
399   while G_UNLIKELY
400     (!g_atomic_int_compare_and_exchange (&tail_mem->tail_read, tail, tail + 1));
401 }
402
403 /**
404  * gst_atomic_queue_length:
405  * @queue: a #GstAtomicQueue
406  *
407  * Get the amount of items in the queue.
408  *
409  * Returns: the number of elements in the queue.
410  *
411  * Since: 0.10.33
412  */
413 guint
414 gst_atomic_queue_length (GstAtomicQueue * queue)
415 {
416   GstAQueueMem *head_mem, *tail_mem;
417   gint head, tail;
418
419   g_return_val_if_fail (queue != NULL, 0);
420
421 #ifdef LOW_MEM
422   g_atomic_int_inc (&queue->num_readers);
423 #endif
424
425   head_mem = g_atomic_pointer_get (&queue->head_mem);
426   head = g_atomic_int_get (&head_mem->head);
427
428   tail_mem = g_atomic_pointer_get (&queue->tail_mem);
429   tail = g_atomic_int_get (&tail_mem->tail_read);
430
431 #ifdef LOW_MEM
432   if (g_atomic_int_dec_and_test (&queue->num_readers))
433     clear_free_list (queue);
434 #endif
435
436   return tail - head;
437 }