4 * Copyright (C) Robert Ham 2002, 2003 (node@users.sourceforge.net)
6 * This program is free software; you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation; either version 2 of the License, or
9 * (at your option) any later version.
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
16 * You should have received a copy of the GNU General Public License
17 * along with this program; if not, write to the Free Software
18 * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
27 #include "lock_free_fifo.h"
29 /** initialise a lock free fifo */
32 lff_init (lff_t * lff, unsigned int size, size_t object_size)
35 lff->object_size = object_size;
38 lff->data = g_malloc (object_size * size);
42 lff_new (unsigned int size, size_t object_size)
46 lff = g_malloc (sizeof (lff_t));
48 lff_init (lff, size, object_size);
54 lff_free (lff_t * lff)
60 lff_destroy (lff_t * lff)
66 /** read an element from the fifo into data.
67 returns 0 on success, non-zero if there were no elements to read */
68 int lff_read (lff_t * lff, void * data) {
69 if (lff->read_index == lff->write_index) {
72 memcpy (data, ((char *)lff->data) + (lff->read_index * lff->object_size),
75 if (lff->read_index >= lff->size) {
82 /** write an element from data to the fifo.
83 returns 0 on success, non-zero if there was no space */
84 int lff_write (lff_t * lff, void * data) {
85 static unsigned int ri;
87 /* got to read read_index only once for safety */
90 /* lots of logic for when we're allowed to write to the fifo which basically
91 boils down to "don't write if we're one element behind the read index" */
92 if ((ri > lff->write_index && ri - lff->write_index > 1) ||
93 (lff->write_index >= ri && lff->write_index != lff->size - 1) ||
94 (lff->write_index >= ri && lff->write_index == lff->size - 1 && ri != 0)) {
96 /* if ((ri > lff->write_index && ri - lff->write_index > 1) ||
97 (lff->write_index >= ri && (lff->write_index != lff->size - 1 || ri != 0))) { */
99 memcpy (((char *)lff->data) + (lff->write_index * lff->object_size),
100 data, lff->object_size);
102 /* FIXME: is this safe? */
104 if (lff->write_index >= lff->size) {
105 lff->write_index = 0;