Scope
SyncQueues.h
1 #pragma once
2 
5 template<class T>
6 class SynchronizedQueue {
7 
8 private:
11 
14 
15 protected:
17  std::deque<T> queue;
18 
20  mutable std::mutex mut;
21 
23  std::condition_variable not_empty;
24 
25 public:
28  }
29 
31  size_t Size() const {
32  std::lock_guard<std::mutex> lock(mut);
33  return queue.size();
34  }
35 
37  void Clear() {
38  std::lock_guard<std::mutex> lock(mut);
39  queue.clear();
40  }
41 
43  void Enqueue(const T& elem) {
44  {
45  std::lock_guard<std::mutex> lock(mut);
46  queue.push_back(elem);
47  }
48  not_empty.notify_one();
49  }
50 
52  void Enqueue(T&& elem) {
53  {
54  std::lock_guard<std::mutex> lock(mut);
55  queue.push_back(elem);
56  }
57  not_empty.notify_one();
58  }
59 
61  T Dequeue() {
62  std::unique_lock<std::mutex> lock(mut);
63  while ( queue.empty() )
64  not_empty.wait(lock);
65  T tmp(queue.front());
66  queue.pop_front();
67  return tmp;
68  }
69 
71  T Dequeue(const std::chrono::milliseconds& timeout) {
72  std::unique_lock<std::mutex> lock(mut);
73  while ( queue.empty() )
74  not_empty.wait_for(lock, timeout);
75  T tmp(queue.front());
76  queue.pop_front();
77  return tmp;
78  }
79 };
80 
81 
void Clear()
Clears the queue.
Definition: SyncQueues.h:37
size_t Size() const
Definition: SyncQueues.h:31
std::condition_variable not_empty
condition variable for not empty notification
Definition: SyncQueues.h:23
std::mutex mut
mutex for protection
Definition: SyncQueues.h:20
void Enqueue(const T &elem)
Enqueues an element and notifies one waiting operation that queue is not empty.
Definition: SyncQueues.h:43
std::deque< T > queue
STL dequeue.
Definition: SyncQueues.h:17
SynchronizedQueue()
We need a default constructor here.
Definition: SyncQueues.h:27
T Dequeue(const std::chrono::milliseconds &timeout)
Dequeues front element, waits timeout if queue is empty.
Definition: SyncQueues.h:71
void Enqueue(T &&elem)
Enqueues an element by moving and notifies one waiting operation that queue is not empty...
Definition: SyncQueues.h:52
A synchronized, thread-safe queue was modeled after ringbuffer example from boost?! and/or a Herb Sutter column?!
Definition: DaqController.h:7
SynchronizedQueue< T > operator=(SynchronizedQueue< T > &)
disable assignment
T Dequeue()
Dequeues front element, waits indefinitely if queue is empty.
Definition: SyncQueues.h:61