PixelBullet  0.0.1
A C++ game engine
Loading...
Searching...
No Matches
command_queue.hpp
1#pragma once
2
3#include <condition_variable>
4#include <functional>
5#include <mutex>
6#include <queue>
7
8namespace PixelBullet
9{
12 {
13 public:
15 bool Push(const std::function<void()>& command)
16 {
17 {
18 std::lock_guard<std::mutex> lock(m_Mutex);
19 if (m_Closed)
20 {
21 return false;
22 }
23 m_Queue.push(command);
24 }
25 m_Cond.notify_one();
26 return true;
27 }
28
30 bool Pop(std::function<void()>& command)
31 {
32 std::unique_lock<std::mutex> lock(m_Mutex);
33 m_Cond.wait(lock, [this]() { return m_Closed || !m_Queue.empty(); });
34
35 if (m_Queue.empty())
36 {
37 return false;
38 }
39
40 command = std::move(m_Queue.front());
41 m_Queue.pop();
42 return true;
43 }
44
45 void Close()
46 {
47 {
48 std::lock_guard<std::mutex> lock(m_Mutex);
49 m_Closed = true;
50 }
51 m_Cond.notify_all();
52 }
53
54 private:
55 std::mutex m_Mutex;
56 std::condition_variable m_Cond;
57 std::queue<std::function<void()>> m_Queue;
58 bool m_Closed = false;
59 };
60} // namespace PixelBullet
A simple thread-safe command queue.
Definition command_queue.hpp:12
bool Pop(std::function< void()> &command)
Blocks until a command is available or the queue is closed.
Definition command_queue.hpp:30
bool Push(const std::function< void()> &command)
Push a new command into the queue.
Definition command_queue.hpp:15