ConcurrentQueue.hh
Go to the documentation of this file.
1 
11 #ifndef __CONCURRENT_QUEUE_H__
12 #define __CONCURRENT_QUEUE_H__
13 
14 #include <queue>
15 #include <mutex>
16 #include <condition_variable>
17 #include <chrono>
18 
19 template<typename T>
20 
29 {
31  std::condition_variable cond_var;
33  std::mutex mutex;
35  std::queue<T> queue;
37  int max_size;
38 
41  public: ConcurrentQueue(int size):
42  max_size(size) {}
43 
47  public: bool enqueue(T data)
48  {
49  bool success = false;
50  std::chrono::milliseconds timeout(200);
51  std::unique_lock<std::mutex> lock(mutex);
52  if (cond_var.wait_for(lock, timeout, [this](){ return !isFull();}))
53  {
54  queue.push(data);
55  success = true;
56  }
57  lock.unlock();
58  cond_var.notify_all();
59  return success;
60  }
61 
65  public: bool dequeue(T &data)
66  {
67  bool success = false;
68  std::chrono::milliseconds timeout(200);
69  std::unique_lock<std::mutex> lock(mutex);
70  if (cond_var.wait_for(lock, timeout, [this](){ return !isEmpty();}))
71  {
72  data = queue.front();
73  queue.pop();
74  success = true;
75  }
76  lock.unlock();
77  cond_var.notify_all();
78  return success;
79  }
80 
82  public: void clear()
83  {
84  std::unique_lock<std::mutex> lock(mutex);
85  while(!isEmpty()) {
86  queue.pop();
87  }
88  lock.unlock();
89  cond_var.notify_all();
90  }
91 
94  private: bool isFull() const
95  {
96  bool full = queue.size() >= max_size;
97  return queue.size() >= max_size;
98  }
99 
102  private: bool isEmpty() const
103  {
104  return queue.size() == 0;
105  }
106 
109  public: int length() const
110  {
111  return queue.size();
112  }
113 };
114 
115 #endif
int length() const
Returns queue&#39;s current size.
Definition: ConcurrentQueue.hh:109
std::queue< T > queue
Generic queue.
Definition: ConcurrentQueue.hh:35
bool enqueue(T data)
Add a data object to tail.
Definition: ConcurrentQueue.hh:47
std::condition_variable cond_var
Condition variable.
Definition: ConcurrentQueue.hh:31
void clear()
Clear queue.
Definition: ConcurrentQueue.hh:82
bool dequeue(T &data)
Remove data object from head.
Definition: ConcurrentQueue.hh:65
int max_size
Max size of queue.
Definition: ConcurrentQueue.hh:37
bool isFull() const
Returns whether queue is full.
Definition: ConcurrentQueue.hh:94
ConcurrentQueue(int size)
Constructor.
Definition: ConcurrentQueue.hh:41
std::mutex mutex
Mutex.
Definition: ConcurrentQueue.hh:33
bool isEmpty() const
Returns whether queue is empty.
Definition: ConcurrentQueue.hh:102
FIFO queue for threadsafe access.
Definition: ConcurrentQueue.hh:28