RTXI  2.4
The Real-Time eXperiment Interface Documentation
fifo.cpp
Go to the documentation of this file.
1 /*
2  The Real-Time eXperiment Interface (RTXI)
3  Copyright (C) 2011 Georgia Institute of Technology, University of Utah, Weill Cornell Medical College
4 
5  This program is free software: you can redistribute it and/or modify
6  it under the terms of the GNU General Public License as published by
7  the Free Software Foundation, either version 3 of the License, or
8  (at your option) any later version.
9 
10  This program is distributed in the hope that it will be useful,
11  but WITHOUT ANY WARRANTY; without even the implied warranty of
12  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13  GNU General Public License for more details.
14 
15  You should have received a copy of the GNU General Public License
16  along with this program. If not, see <http://www.gnu.org/licenses/>.
17 
18 */
19 
20 #include <debug.h>
21 #include <fifo.h>
22 #include <string.h>
23 
24 #define AVAILABLE ((size+wptr-rptr)%size)
25 
26 Fifo::Fifo(size_t s):rptr(0), wptr(0), size(s)
27 {
28  data = new char[size];
29 
30  pthread_mutex_init(&mutex,NULL);
31  pthread_cond_init(&data_available,NULL);
32 }
33 
35 {
36  if (data) delete[] data;
37 
38  pthread_mutex_destroy(&mutex);
39  pthread_cond_destroy(&data_available);
40 }
41 
42 size_t Fifo::read(void *buffer,size_t n,bool blocking)
43 {
44  // Acquire the data lock
45  if (blocking)
46  pthread_mutex_lock(&mutex);
47  else if (pthread_mutex_trylock(&mutex) != 0)
48  return 0;
49 
50  // Check that enough data is available
51  if (AVAILABLE < n){
52  if (blocking)
53  {
54  do
55  {
56  pthread_cond_wait(&data_available,&mutex);
57  }
58  while (AVAILABLE < n);
59  }
60  else
61  {
62  pthread_mutex_unlock(&mutex);
63  return 0;
64  }
65  }
66  // Copy the data from the fifo
67  if (size-rptr < n)
68  {
69  size_t m = size-rptr;
70  memcpy(buffer,data+rptr,m);
71  memcpy(reinterpret_cast<char *>(buffer)+m,data,n-m);
72  }
73  else
74  memcpy(buffer,data+rptr,n);
75  rptr = (rptr+n)%size;
76 
77  pthread_mutex_unlock(&mutex);
78  return n;
79 }
80 
81 size_t Fifo::write(const void *buffer,size_t n)
82 {
83  if (n >= size-AVAILABLE)
84  {
85  ERROR_MSG("Fifo::write : fifo full, data lost\n");
86  return 0;
87  }
88 
89  if (n > size-wptr)
90  {
91  size_t m = size-wptr;
92  memcpy(data+wptr,buffer,m);
93  memcpy(data,reinterpret_cast<const char *>(buffer)+m,n-m);
94  }
95  else
96  memcpy(data+wptr,buffer,n);
97  wptr = (wptr+n)%size;
98 
99  pthread_cond_signal(&data_available);
100 
101  return n;
102 }
ERROR_MSG
void ERROR_MSG(const std::string &errmsg,...)
Definition: debug.cpp:27
Fifo::read
size_t read(void *, size_t, bool=true)
Definition: fifo.cpp:42
Fifo::Fifo
Fifo(size_t)
Definition: fifo.cpp:26
fifo.h
AVAILABLE
#define AVAILABLE
Definition: fifo.cpp:24
Fifo::write
size_t write(const void *, size_t)
Definition: fifo.cpp:81
Fifo::~Fifo
~Fifo(void)
Definition: fifo.cpp:34
debug.h