Kurlyk
Loading...
Searching...
No Matches
EventQueue.hpp
Go to the documentation of this file.
1#pragma once
2#ifndef _KURLYK_EVENT_QUEUE_HPP_INCLUDED
3#define _KURLYK_EVENT_QUEUE_HPP_INCLUDED
4
7
8#include <queue>
9#include <mutex>
10#include <condition_variable>
11
12namespace kurlyk::utils {
13
16 template<class T>
17 class EventQueue {
18 public:
21 void push_event(T&& event) {
22 std::lock_guard<std::mutex> lock(m_mutex);
23 m_events.emplace(std::move(event));
24 m_cond_var.notify_one();
25 }
26
29 void push_event(const T& event) {
30 std::lock_guard<std::mutex> lock(m_mutex);
31 m_events.push(event);
32 m_cond_var.notify_one();
33 }
34
38 std::unique_lock<std::mutex> lock(m_mutex);
39 m_cond_var.wait(lock, [this] { return !m_events.empty(); });
40 T event = std::move(m_events.front());
41 m_events.pop();
42 return event;
43 }
44
47 bool has_events() const {
48 std::lock_guard<std::mutex> lock(m_mutex);
49 return !m_events.empty();
50 }
51
52 private:
53 std::queue<T> m_events;
54 mutable std::mutex m_mutex;
55 std::condition_variable m_cond_var;
56 };
57
58} // namespace kurlyk::utils
59
60#endif // _KURLYK_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.