PixelBullet  0.0.1
A C++ game engine
Loading...
Searching...
No Matches
CommandQueue.hpp
1#pragma once
2
3#include <condition_variable>
4#include <functional>
5#include <mutex>
6#include <queue>
7#include <chrono>
8
9namespace PixelBullet
10{
13 {
14 public:
16 void Push(const std::function<void()>& command)
17 {
18 {
19 std::lock_guard<std::mutex> lock(m_Mutex);
20 m_Queue.push(command);
21 }
22 m_Cond.notify_one();
23 }
24
27 bool Pop(std::function<void()>& command, std::chrono::milliseconds waitDuration)
28 {
29 std::unique_lock<std::mutex> lock(m_Mutex);
30 if (m_Cond.wait_for(lock, waitDuration, [this]() { return !m_Queue.empty(); }))
31 {
32 command = m_Queue.front();
33 m_Queue.pop();
34 return true;
35 }
36 return false;
37 }
38
40 void NotifyAll()
41 {
42 m_Cond.notify_all();
43 }
44
45 private:
46 std::mutex m_Mutex;
47 std::condition_variable m_Cond;
48 std::queue<std::function<void()>> m_Queue;
49 };
50} // namespace PixelBullet
A simple thread-safe command queue.
Definition CommandQueue.hpp:13
void Push(const std::function< void()> &command)
Push a new command into the queue.
Definition CommandQueue.hpp:16
bool Pop(std::function< void()> &command, std::chrono::milliseconds waitDuration)
Definition CommandQueue.hpp:27
void NotifyAll()
Notifies all waiting threads.
Definition CommandQueue.hpp:40