Clean-ups
[invirt/third/libt4.git] / rpc / fifo.h
1 #ifndef fifo_h
2 #define fifo_h
3
4 #include "types.h"
5
6 template<class T>
7 class fifo {
8     public:
9         fifo(size_t limit=0) : max_(limit) {}
10
11         bool enq(T e, bool blocking=true) {
12             lock ml(m_);
13             while (max_ && q_.size() >= max_) {
14                 if (!blocking)
15                     return false;
16                 has_space_c_.wait(ml);
17             }
18             q_.push_back(e);
19             non_empty_c_.notify_one();
20             return true;
21         }
22
23         T deq() {
24             lock ml(m_);
25             while(q_.empty())
26                 non_empty_c_.wait(ml);
27             T t = q_.front();
28             q_.pop_front();
29             if (max_ && q_.size() < max_)
30                 has_space_c_.notify_one();
31             return t;
32         }
33
34     private:
35         std::list<T> q_;
36         std::mutex m_;
37         cond non_empty_c_; // q went non-empty
38         cond has_space_c_; // q is not longer overfull
39         size_t max_; // maximum capacity of the queue, block enq threads if exceeds this limit
40 };
41
42 #endif