Kurlyk
Loading...
Searching...
No Matches
EventQueue.hpp
Go to the documentation of this file.
1#pragma once
2#ifndef KURLYK_HEADER_KURLYK_UTILS_EVENT_QUEUE_HPP_INCLUDED
3#define KURLYK_HEADER_KURLYK_UTILS_EVENT_QUEUE_HPP_INCLUDED
4
7
8#include <queue>
9#include <mutex>
10#include <condition_variable>
11
12namespace kurlyk {
13namespace utils {
14
17 template<class T>
18 class EventQueue {
19 public:
22 void push_event(T&& event) {
23 std::lock_guard<std::mutex> lock(m_mutex);
24 m_events.emplace(std::move(event));
25 m_cond_var.notify_one();
26 }
27
30 void push_event(const T& event) {
31 std::lock_guard<std::mutex> lock(m_mutex);
32 m_events.push(event);
33 m_cond_var.notify_one();
34 }
35
39 std::unique_lock<std::mutex> lock(m_mutex);
40 m_cond_var.wait(lock, [this] { return !m_events.empty(); });
41 T event = std::move(m_events.front());
42 m_events.pop();
43 return event;
44 }
45
48 bool has_events() const {
49 std::lock_guard<std::mutex> lock(m_mutex);
50 return !m_events.empty();
51 }
52
53 private:
54 std::queue<T> m_events;
55 mutable std::mutex m_mutex;
56 std::condition_variable m_cond_var;
57 };
58
59} // namespace utils
60} // namespace kurlyk
61
62#endif // KURLYK_HEADER_KURLYK_UTILS_EVENT_QUEUE_HPP_INCLUDED
A thread-safe event queue that supports blocking and non-blocking event retrieval.
T pop_event()
Removes and returns an event from the queue (blocks if the queue is empty).
void push_event(T &&event)
Adds an event to the queue using move semantics.
void push_event(const T &event)
Adds a copy of an event to the queue and notifies any waiting threads.
std::queue< T > m_events
Queue to store events.
bool has_events() const
Checks if there are events in the queue.
std::condition_variable m_cond_var
Condition variable for blocking until events are available.
std::mutex m_mutex
Mutex to protect queue access.
Primary namespace for the Kurlyk library, encompassing initialization, request management,...