5 * Copyright (C) Robert Ham 2002, 2003 (node@users.sourceforge.net)
7 * Modification for MLT:
8 * Copyright (C) 2004 Ushodaya Enterprises Limited
9 * Author: Dan Dennedy <dan@dennedy.org>
11 * This program is free software; you can redistribute it and/or modify
12 * it under the terms of the GNU General Public License as published by
13 * the Free Software Foundation; either version 2 of the License, or
14 * (at your option) any later version.
16 * This program is distributed in the hope that it will be useful,
17 * but WITHOUT ANY WARRANTY; without even the implied warranty of
18 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
19 * GNU General Public License for more details.
21 * You should have received a copy of the GNU General Public License
22 * along with this program; if not, write to the Free Software
23 * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
32 #include "lock_free_fifo.h"
34 /** initialise a lock free fifo */
37 lff_init (lff_t * lff, unsigned int size, size_t object_size)
40 lff->object_size = object_size;
43 lff->data = g_malloc (object_size * size);
47 lff_new (unsigned int size, size_t object_size)
51 lff = g_malloc (sizeof (lff_t));
53 lff_init (lff, size, object_size);
59 lff_free (lff_t * lff)
65 lff_destroy (lff_t * lff)
71 /** read an element from the fifo into data.
72 returns 0 on success, non-zero if there were no elements to read */
73 int lff_read (lff_t * lff, void * data) {
74 if (lff->read_index == lff->write_index) {
77 memcpy (data, ((char *)lff->data) + (lff->read_index * lff->object_size),
80 if (lff->read_index >= lff->size) {
87 /** write an element from data to the fifo.
88 returns 0 on success, non-zero if there was no space */
89 int lff_write (lff_t * lff, void * data) {
90 static unsigned int ri;
92 /* got to read read_index only once for safety */
95 /* lots of logic for when we're allowed to write to the fifo which basically
96 boils down to "don't write if we're one element behind the read index" */
97 if ((ri > lff->write_index && ri - lff->write_index > 1) ||
98 (lff->write_index >= ri && lff->write_index != lff->size - 1) ||
99 (lff->write_index >= ri && lff->write_index == lff->size - 1 && ri != 0)) {
101 /* if ((ri > lff->write_index && ri - lff->write_index > 1) ||
102 (lff->write_index >= ri && (lff->write_index != lff->size - 1 || ri != 0))) { */
104 memcpy (((char *)lff->data) + (lff->write_index * lff->object_size),
105 data, lff->object_size);
107 /* FIXME: is this safe? */
109 if (lff->write_index >= lff->size) {
110 lff->write_index = 0;