| 18 | } |
| 19 | |
| 20 | template <typename T> class SafeQueue { |
| 21 | std::queue<T> q; |
| 22 | std::mutex mtx; |
| 23 | std::condition_variable cond; |
| 24 | |
| 25 | public: |
| 26 | T &front() { |
| 27 | std::unique_lock<std::mutex> mlock(mtx); |
| 28 | while (q.empty()) |
| 29 | cond.wait(mlock); |
| 30 | return q.front(); |
| 31 | } |
| 32 | |
| 33 | void pop_front() { |
| 34 | std::unique_lock<std::mutex> mlock(mtx); |
| 35 | while (q.empty()) |
| 36 | cond.wait(mlock); |
| 37 | q.pop(); |
| 38 | } |
| 39 | |
| 40 | void push_back(const T &item) { |
| 41 | std::unique_lock<std::mutex> mlock(mtx); |
| 42 | q.push(item); |
| 43 | mlock.unlock(); // unlock before notificiation to minimize mutex con |
| 44 | cond.notify_one(); // notify one waiting thread |
| 45 | } |
| 46 | |
| 47 | int size() { |
| 48 | std::unique_lock<std::mutex> mlock(mtx); |
| 49 | int size = q.size(); |
| 50 | mlock.unlock(); |
| 51 | return size; |
| 52 | } |
| 53 | }; |
| 54 | |
| 55 | class TimeBomb { |
| 56 | std::function<void()> cb; |