📄 fifo.h
字号:
// Larbin// Sebastien Ailleret// 09-11-99 -> 20-01-00/* standard fifo in RAM */#ifndef FIFO_H#define FIFO_H#define std_size 100#include <pthread.h>template <class T>class Fifo : public GenericFifo<T> { protected: uint size; T **tab; pthread_mutex_t lock; pthread_cond_t nonEmpty; public: /* Specific constructor */ Fifo (uint size = std_size); /* Destructor */ virtual ~Fifo (); /* Reduce the size of tab if necessary */ void reduce (); /* get the first object */ virtual T *get (); /* get the first object (non totally blocking) * return NULL if there is none */ virtual T *tryGet (); /* add an object in the Fifo */ virtual void put (T *obj); /* add an object in the Fifo * never block !!! */ virtual void putForce (T *obj); /* how many itmes are there inside ? */ virtual int getLength ();};template <class T>Fifo<T>::Fifo (uint size = std_size) { tab = new T*[size]; this->size = size; in = 0; out = 0; pthread_mutex_init (&lock, NULL); pthread_cond_init (&nonEmpty, NULL);}template <class T>Fifo<T>::~Fifo () { delete [] tab; pthread_mutex_destroy (&lock); pthread_cond_destroy (&nonEmpty);}template <class T>void Fifo<T>::reduce () { if (size > std_size && ((in + size - out) % size)*3 < size) { // if the tab is too big, reduce it T **tmp = new T*[size/2]; uint i; for (i=0; ((out+i) % size) != in; i++) { tmp[i] = tab[(out+i) % size]; } out = 0; in = i; size /= 2; delete [] tab; tab = tmp; }}template <class T>T *Fifo<T>::get () { T *tmp; pthread_mutex_lock(&lock); while (in == out) { pthread_cond_wait(&nonEmpty, &lock); } tmp = tab[out]; out = (out + 1) % size; reduce(); pthread_mutex_unlock(&lock); return tmp;}template <class T>T *Fifo<T>::tryGet () { T *tmp = NULL; pthread_mutex_lock(&lock); if (in != out) { // The stack is not empty tmp = tab[out]; out = (out + 1) % size; reduce(); } pthread_mutex_unlock(&lock); return tmp;}template <class T>void Fifo<T>::put (T *obj) { pthread_mutex_lock(&lock); tab[in] = obj; if (in == out) { pthread_cond_broadcast(&nonEmpty); } in = (in + 1) % size; if (in == out) { T **tmp; tmp = new T*[2*size]; for (uint i=out; i<size; i++) { tmp[i] = tab[i]; } for (uint i=0; i<in; i++) { tmp[i+size] = tab[i]; } in += size; size *= 2; delete [] tab; tab = tmp; } pthread_mutex_unlock(&lock);}template <class T>void Fifo<T>::putForce (T *obj) { put(obj);}template <class T>int Fifo<T>::getLength () { int tmp; pthread_mutex_lock(&lock); tmp = (in + size - out) % size; pthread_mutex_unlock(&lock); return tmp;}#endif // FIFO_H
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -