SynchronizedQueue.hpp
Go to the documentation of this file.
1 // @formatter:off
2 //
3 // Balau core C++ library
4 //
5 // Copyright (C) 2008 Bora Software (contact@borasoftware.com)
6 //
7 // Licensed under the Boost Software License - Version 1.0 - August 17th, 2003.
8 // See the LICENSE file for the full license text.
9 //
10 
16 
17 #ifndef COM_BORA_SOFTWARE__BALAU_CONTAINER__SYNCHRONISED_QUEUE
18 #define COM_BORA_SOFTWARE__BALAU_CONTAINER__SYNCHRONISED_QUEUE
19 
22 #include <Balau/Type/StdTypes.hpp>
23 
24 #include <list>
25 #include <mutex>
26 
27 namespace Balau::Container {
28 
37 template <typename T> class SynchronizedQueue : public Queue<T> {
38  public: void enqueue(T && element) override {
39  std::lock_guard<std::mutex> lock(mutex);
40  elements.push_back(std::move(element));
41  }
42 
48  public: T dequeue() override {
49  std::lock_guard<std::mutex> lock(mutex);
50 
51  if (elements.empty()) {
52  ThrowBalauException(Exception::EmptyException, "Synchronised queue is empty.");
53  }
54 
55  T element = std::move(elements.front());
56  elements.pop_front();
57  return element;
58  }
59 
60  public: bool empty() const override {
61  std::lock_guard<std::mutex> lock(mutex);
62  return elements.size() == 0;
63  }
64 
66 
67  private: std::list<T> elements;
68  private: mutable std::mutex mutex;
69 };
70 
71 } // namespace Balau::Container
72 
73 #endif // COM_BORA_SOFTWARE__BALAU_CONTAINER__SYNCHRONISED_QUEUE
T dequeue() override
Dequeue an object.
Definition: SynchronizedQueue.hpp:48
Base interface for queues.
Definition: Queue.hpp:27
Base interface for queues.
#define ThrowBalauException(ExceptionClass,...)
Throw a Balau style exception, with implicit file and line number, and optional stacktrace.
Definition: BalauException.hpp:45
Various container classes, apart from interprocess containers.
Definition: ArrayBlockingQueue.hpp:25
Balau exceptions for containers.
Thrown when a request is made for an element but no elements are available.
Definition: ContainerExceptions.hpp:46
A queue that uses a mutex to synchronise enqueue and dequeue calls.
Definition: SynchronizedQueue.hpp:37
bool empty() const override
Returns true if the queue is empty.
Definition: SynchronizedQueue.hpp:60
Core includes, typedefs and functions.
void enqueue(T &&element) override
Enqueue an object, moving the supplied element.
Definition: SynchronizedQueue.hpp:38