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
| template <typename T, typename D = std::deque<T> > class ThreadQueue { public: typedef D queue_type; bool pop_front(T& t, size_t millsecond); void push_back(T& t); void push_front(T& t); void swap(queue_type& q); void clear(); bool empty(); auto begin(); auto end();
protected: queue_type queue_; size_t size_;
private: std::mutex mutex_; std::condition_variable cond_; };
template <typename T, typename D> bool ThreadQueue<T, D>::pop_front(T& t, size_t millsecond) { std::unique_lock<std::mutex> lock(mutex_); while (queue_.empty()) { cond_.wait(lock); }
assert(!queue_.empty()); t = queue_.front(); queue_.pop_front(); size_--; return true; }
template <typename T, typename D> void ThreadQueue<T, D>::push_back(T& t) { std::unique_lock<std::mutex> lock(mutex_); queue_.push_back(t); size_++; cond_.notify_one(); }
template <typename T, typename D> void ThreadQueue<T, D>::push_front(T& t) { std::unique_lock<std::mutex> lock(mutex_); queue_.push_front(t); size_++; cond_.notify_one(); }
template <typename T, typename D> void ThreadQueue<T, D>::clear() { std::unique_lock<std::mutex> lock(mutex_); queue_.clear(); size_ = 0; }
template <typename T, typename D> bool ThreadQueue<T, D>::empty() { return queue_.empty(); }
template <typename T, typename D> auto ThreadQueue<T, D>::begin() { std::unique_lock<std::mutex> lock(mutex_); return queue_.begin(); }
template <typename T, typename D> auto ThreadQueue<T, D>::end() { std::unique_lock<std::mutex> lock(mutex_); return queue_.end(); }
template <typename T, typename D> void ThreadQueue<T, D>::swap(D& q) { std::unique_lock<std::mutex> lock(mutex_); q.swap(queue_); }
|