Argentum Online - Servidor
blocking_queue.h
1 #ifndef BLOCKING_QUEUE_H
2 #define BLOCKING_QUEUE_H
3 
4 #include <condition_variable>
5 #include <mutex>
6 #include <queue>
7 #include <stdexcept>
8 #include <utility>
9 
10 class ClosedBlockingQueueException : std::exception {
11  public:
13 
14  virtual const char* what() const noexcept {
15  return "Se cerrĂ³ la queue bloqueante";
16  }
17 
19 };
20 
21 template <typename T>
23  private:
24  std::queue<T> queue;
25  std::mutex mutex;
26  std::condition_variable cond_var;
27  bool _is_closed;
28  bool wait_depleted;
29 
30  bool meets_deplete_cond() const {
31  return wait_depleted ? queue.empty() : true;
32  }
33 
34  public:
35  BlockingQueue() : _is_closed(false), wait_depleted(false) {}
36 
37  BlockingQueue(const BlockingQueue<T>& other)
38  : queue(other.queue), _is_closed(other._is_closed) {}
39 
40  BlockingQueue<T>& operator=(const BlockingQueue<T>& other) {
41  queue = std::queue<T>(other.queue);
42  _is_closed = other._is_closed;
43  return *this;
44  }
45 
47  queue = std::move(other.queue);
48  _is_closed = other._is_closed;
49  other._is_closed = true;
50  }
51 
52  bool is_empty() const {
53  return queue.empty();
54  }
55 
56  void push(T t) {
57  std::unique_lock<std::mutex> lock(mutex);
58  queue.push(t);
59  cond_var.notify_all();
60  }
61 
62  T pop() {
63  std::unique_lock<std::mutex> lock(mutex);
64  while (queue.empty()) {
65  if (!_is_closed)
66  cond_var.wait(lock);
67  else
69  }
70  // if (meets_deplete_cond())
71  // throw ClosedBlockingQueueException();
72  T t = queue.front();
73  queue.pop();
74  return t;
75  }
76 
77  void close(bool deplete = true) {
78  std::unique_lock<std::mutex> lock(mutex);
79  wait_depleted = deplete;
80  _is_closed = true;
81  cond_var.notify_all();
82  }
83 
84  bool is_closed() const {
85  return _is_closed && meets_deplete_cond();
86  }
87 
88  ~BlockingQueue() {}
89 };
90 
91 #endif // BLOCKING_QUEUE_H
ClosedBlockingQueueException
Definition: blocking_queue.h:10
BlockingQueue
Definition: blocking_queue.h:22