R-Type
SafeQueue.hpp
Go to the documentation of this file.
1 /*
2 ** EPITECH PROJECT, 2023
3 ** Plazza
4 ** File description:
5 ** SafeQueue
6 */
7 
8 #ifndef SAFEQUEUE_HPP_
9 #define SAFEQUEUE_HPP_
10 #include "ISafeQueue.hpp"
11 #include <condition_variable>
12 #include <mutex>
13 #include <queue>
14 
17 template <typename T>
18 class SafeQueue : public ISafeQueue<T>
19 {
20  public:
21  SafeQueue() = default;
23  ~SafeQueue() = default;
26  void push(T value) override
27  {
28  std::unique_lock<std::mutex> l(mutex);
29  queue.push(value);
30  cond.notify_one();
31  }
32 
38  bool tryPop(T &value) override
39  {
40  std::unique_lock<std::mutex> l(mutex);
41  if (queue.size() == 0)
42  return false;
43  value = queue.front();
44  queue.pop();
45  return true;
46  }
47 
51  T pop() override
52  {
53  std::unique_lock<std::mutex> l(mutex);
54  if (queue.size() == 0)
55  cond.wait(l);
56  T value = queue.front();
57  queue.pop();
58  return value;
59  }
60 
63  size_t size() const { return queue.size(); }
64 
65  private:
66  std::queue<T> queue;
67  std::mutex mutex;
68  std::condition_variable cond;
69 };
70 #endif
Interface for queue that is thread safe.
Definition: ISafeQueue.hpp:14
A queue class that is thread safe.
Definition: SafeQueue.hpp:19
bool tryPop(T &value) override
Try to pop a value from the queue, lock a mutex while trying to pop the value.
Definition: SafeQueue.hpp:38
T pop() override
Pop a value from the queue, lock a mutex and wait if the queue is empty.
Definition: SafeQueue.hpp:51
~SafeQueue()=default
Destructor.
SafeQueue()=default
void push(T value) override
Push in queue, lock a mutex while pushing the value.
Definition: SafeQueue.hpp:26
size_t size() const
Returns the current size of the queue.
Definition: SafeQueue.hpp:63
@ T
Definition: Keyboard.hpp:49