larbin源碼分析--SyncFifo

//同步隊列中的每一個操做都須要先加鎖,後解鎖,以避免發生同步問題。 ide

 

template <class T> ui

class SyncFifo { this

 protected: spa

  uint in, out;          //隊列的兩個標誌位,一個入口標誌位,一個出口標誌位 orm

  uint size;            //隊列長度 隊列

  T **tab; ci

#ifdef THREAD_OUTPUT get

  pthread_mutex_t lock;            //由於這個隊列是同步的,因此有鎖 同步

  pthread_cond_t nonEmpty; it

#endif

 

 public:

  /* Specific constructor */

  SyncFifo (uint size = std_size);

 

  /* Destructor */

  ~SyncFifo ();

 

  /* get the first object */

  T *get ();                         //得到隊列頭

 

  /* get the first object (non totally blocking)

   * return NULL if there is none

   */

  T *tryGet ();

 

  /* add an object in the Fifo */

  void put (T *obj);                      //入隊

 

  /* how many itmes are there inside ? */

  int getLength ();                      //獲取體積

};

 

template <class T>

SyncFifo<T>::SyncFifo (uint size) {

  tab = new T*[size];

  this->size = size;

  in = 0;

  out = 0;

  mypthread_mutex_init (&lock, NULL);

  mypthread_cond_init (&nonEmpty, NULL);

}

 

template <class T>

SyncFifo<T>::~SyncFifo () {

  delete [] tab;

  mypthread_mutex_destroy (&lock);

  mypthread_cond_destroy (&nonEmpty);

}

 

template <class T>

T *SyncFifo<T>::get () {

  T *tmp;

  mypthread_mutex_lock(&lock);

  mypthread_cond_wait(in == out, &nonEmpty, &lock);

  tmp = tab[out];

  out = (out + 1) % size;

  mypthread_mutex_unlock(&lock);

  return tmp;

}

 

template <class T>

T *SyncFifo<T>::tryGet () {         //每次獲取時都要先加鎖,後解鎖

  T *tmp = NULL;

  mypthread_mutex_lock(&lock);

  if (in != out) {

         // The stack is not empty

         tmp = tab[out];

         out = (out + 1) % size;

  }

  mypthread_mutex_unlock(&lock);

  return tmp;

}

 

template <class T>

void SyncFifo<T>::put (T *obj) {

  mypthread_mutex_lock(&lock);

  tab[in] = obj;

  if (in == out) {

    mypthread_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;

  }

  mypthread_mutex_unlock(&lock);

}

 

template <class T>

int SyncFifo<T>::getLength () {

  int tmp;

  mypthread_mutex_lock(&lock);

  tmp = (in + size - out) % size;

  mypthread_mutex_unlock(&lock);

  return tmp;

}

 

#endif // SYNCFIFO_H

相關文章
相關標籤/搜索