synchronizedqueue.h 1.74 KB
Newer Older
wangdawei's avatar
wangdawei committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94
#ifndef SYNCHRONIZEDQUEUE_H
#define SYNCHRONIZEDQUEUE_H

#endif // SYNCHRONIZEDQUEUE_H

#include <boost/thread/thread.hpp>
#include <boost/asio.hpp>
#include <queue>
#include <deque>
#pragma once

template<typename T>
class SynchronizedQueue
{
  public:

    SynchronizedQueue () :
      queue_(), mutex_(), cond_(), request_to_end_(false), enqueue_data_(true) { }

    void
    enqueue (const T& data)
    {
      boost::unique_lock<boost::mutex> lock (mutex_);

      if (enqueue_data_)
      {
        queue_.push (data);
        cond_.notify_one ();
      }
    }

    bool
    dequeue (T& result)
    {
      boost::unique_lock<boost::mutex> lock (mutex_);

      while (queue_.empty () && (!request_to_end_))
      {
        cond_.wait (lock);
      }

      if (request_to_end_)
      {
        doEndActions ();
        return false;
      }

      result = queue_.front ();
      queue_.pop ();

      return true;
    }

    void
    stopQueue ()
    {
      boost::unique_lock<boost::mutex> lock (mutex_);
      request_to_end_ = true;
      cond_.notify_all ();
    }

    unsigned int
    size ()
    {
      boost::unique_lock<boost::mutex> lock (mutex_);
      return static_cast<unsigned int> (queue_.size ());
    }

    bool
    isEmpty () const
    {
      boost::unique_lock<boost::mutex> lock (mutex_);
      return (queue_.empty ());
    }

  private:
    void
    doEndActions ()
    {
      enqueue_data_ = false;

      while (!queue_.empty ())
      {
        queue_.pop ();
      }
    }

    std::queue<T> queue_;              // Use STL queue to store data
    mutable boost::mutex mutex_;       // The mutex to synchronise on
    boost::condition_variable cond_;   // The condition to wait for

    bool request_to_end_;
    bool enqueue_data_;
};