VoltMod
C++23 framework for CS2 server plugins
Loading...
Searching...
No Matches
GameThreadQueue.hpp
Go to the documentation of this file.
1#pragma once
2
3#include <atomic>
4#include <functional>
5#include <mutex>
6#include <utility>
7#include <vector>
8
9namespace VoltMod
10{
11
12/** @brief Callbacks worker threads hand to the game thread: @ref Push from any thread, @ref RunAll on
13 * the game thread. */
15{
16public:
17 void Push(std::move_only_function<void()> completion)
18 {
19 std::lock_guard lock(_mutex);
20 _waiting.push_back(std::move(completion));
21 _any.store(true, std::memory_order_release);
22 }
23
24 /** Runs what was pushed so far; anything pushed meanwhile waits for the next call. */
25 void RunAll()
26 {
27 // Called every frame, so an empty queue takes no lock.
28 if (!_any.load(std::memory_order_acquire))
29 {
30 return;
31 }
32 std::vector<std::move_only_function<void()>> ready;
33 {
34 std::lock_guard lock(_mutex);
35 ready.swap(_waiting);
36 _any.store(false, std::memory_order_relaxed);
37 }
38 for (auto& completion : ready)
39 {
40 completion();
41 }
42 }
43
44 /** Drops what is waiting, unrun. */
45 void Clear()
46 {
47 std::lock_guard lock(_mutex);
48 _waiting.clear();
49 _any.store(false, std::memory_order_relaxed);
50 }
51
52private:
53 std::mutex _mutex;
54 std::vector<std::move_only_function<void()>> _waiting;
55 std::atomic<bool> _any{false};
56};
57
58} // namespace VoltMod
Callbacks worker threads hand to the game thread: Push from any thread, RunAll on the game thread.
void Push(std::move_only_function< void()> completion)
static std::string ReadFile(const std::filesystem::path &path)
Definition Loader.cpp:56