Bredbandskollen CLI  1.2
Asynchronous network task engine
msgqueue.h
1 #pragma once
2 
3 #include <queue>
4 #include <mutex>
5 #include <condition_variable>
6 
14 template <class T>
15 class MsgQueue {
16 public:
17  MsgQueue() :
18  queue(),
19  mutex(),
20  cond() {
21  }
22 
23  ~MsgQueue() {
24  }
25 
27  void push(T t) {
28  std::lock_guard<std::mutex> lock(mutex);
29  queue.push(t);
30  cond.notify_one();
31  }
32 
34  bool empty() {
35  std::unique_lock<std::mutex> lock(mutex);
36  return queue.empty();
37  }
38 
43  std::unique_lock<std::mutex> lock(mutex);
44  while (queue.empty()) {
45  cond.wait(lock);
46  }
47  T val = queue.front();
48  queue.pop();
49  return val;
50  }
51 
58  bool fetch(T &val)
59  {
60  std::unique_lock<std::mutex> lock(mutex);
61  if (queue.empty())
62  return false;
63  val = queue.front();
64  queue.pop();
65  return true;
66  }
67 
68 private:
69  std::queue<T> queue;
70  mutable std::mutex mutex;
71  std::condition_variable cond;
72 };
Thread safe queue.
Definition: msgqueue.h:15
bool empty()
Return true if the queue is empty.
Definition: msgqueue.h:34
void push(T t)
Add object at the end of the queue.
Definition: msgqueue.h:27
T pop_blocking()
Wait until there is an object in the queue, then remove and return the first object.
Definition: msgqueue.h:42
bool fetch(T &val)
A non-blocking pop.
Definition: msgqueue.h:58