📄 maxedsizedfifo.h
字号:
// Larbin// Sebastien Ailleret// 09-11-99 -> 20-01-00/* this fifo cannot grow */#ifndef MAXFIFO_H#define MAXFIFO_H#include <assert.h>#include <pthread.h>#include "xutils/GenericFifo.h"template <class T>class MaxedSizedFifo : public GenericFifo<T> { private: uint size; // Phisical size uint msize; // Logical size T **tab; pthread_mutex_t lock; pthread_cond_t nonEmpty; pthread_cond_t nonFull; public: /* Specific constructor */ MaxedSizedFifo (uint size, uint margin); /* Destructor */ virtual ~MaxedSizedFifo (); /* 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>MaxedSizedFifo<T>::MaxedSizedFifo (uint size, uint margin) { this->size = size + margin + 1; tab = new T*[this->size]; in = 0; out = 0; msize = size; pthread_mutex_init (&lock, NULL); pthread_cond_init (&nonEmpty, NULL); pthread_cond_init (&nonFull, NULL);}template <class T>MaxedSizedFifo<T>::~MaxedSizedFifo () { delete [] tab; pthread_mutex_destroy (&lock); pthread_cond_destroy (&nonEmpty); pthread_cond_destroy (&nonFull);}template <class T>T *MaxedSizedFifo<T>::get () { T *tmp; pthread_mutex_lock(&lock); while (in == out) { pthread_cond_wait(&nonEmpty, &lock); } tmp = tab[out]; out = (out + 1) % size; if (((in + size - out) % size) == msize - 1) { pthread_cond_broadcast(&nonFull); } pthread_mutex_unlock(&lock); return tmp;}template <class T>T *MaxedSizedFifo<T>::tryGet () { T *tmp = NULL; pthread_mutex_lock(&lock); if (in != out) { // The stack is not empty tmp = tab[out]; out = (out + 1) % size; if (((in + size - out) % size) == msize - 1) { pthread_cond_broadcast(&nonFull); } } pthread_mutex_unlock(&lock); return tmp;}template <class T>void MaxedSizedFifo<T>::put (T *obj) { pthread_mutex_lock(&lock); while (((in + size - out) % size) >= msize) { pthread_cond_wait(&nonFull, &lock); } tab[in] = obj; if (in == out) { pthread_cond_broadcast(&nonEmpty); } in = (in + 1) % size; pthread_mutex_unlock(&lock);}template <class T>void MaxedSizedFifo<T>::putForce (T *obj) { pthread_mutex_lock(&lock); tab[in] = obj; if (in == out) { pthread_cond_broadcast(&nonEmpty); } in = (in + 1) % size; assert(in != out); pthread_mutex_unlock(&lock);}template <class T>int MaxedSizedFifo<T>::getLength () { int tmp; pthread_mutex_lock(&lock); tmp = (in + size - out) % size; pthread_mutex_unlock(&lock); return tmp;}#endif // MAXFIFO_H
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -