Debian Codegraph @

Source/Core/Common/WorkQueueThread.h

raw symbols SCIP
1 // Copyright 2017 Dolphin Emulator Project
2 // SPDX-License-Identifier: GPL-2.0-or-later
3
4 #pragma once
5
6 #include <functional>
7 #include <future>
8 #include <mutex>
9 #include <string>
10 #include <thread>
11
12 #include "Common/Event.h"
13 #include "Common/SPSCQueue.h"
14 #include "Common/Thread.h"
15
16 namespace Common
17 {
18 namespace detail
19 {
20 template <typename T, bool IsSingleProducer>
21 class WorkQueueThreadBase final
22 {
23 public:
24 using FunctionType = std::function<void(T)>;
25
26 WorkQueueThreadBase() = default;
27 WorkQueueThreadBase(std::string name, FunctionType function)
28 {
29 Reset(std::move(name), std::move(function));
30 }
31 ~WorkQueueThreadBase() { Shutdown(); }
32
33 // Shuts the current work thread down (if any) and starts a new thread with the given function
34 // Note: Some consumers of this API push items to the queue before starting the thread.
35 void Reset(std::string name, FunctionType function)
36 {
37 auto lg = GetLockGuard();
38 Shutdown();
39 m_thread = std::thread(std::bind_front(&WorkQueueThreadBase::ThreadLoop, this), std::move(name),
40 std::move(function));
41 }
42
43 // Adds an item to the work queue
44 template <typename... Args>
45 void EmplaceItem(Args&&... args)
46 {
47 auto lg = GetLockGuard();
48 m_items.Emplace(std::forward<Args>(args)...);
49 m_event.Set();
50 }
51 void Push(T&& item) { EmplaceItem(std::move(item)); }
52 void Push(const T& item) { EmplaceItem(item); }
53
54 // Empties the queue, skipping all work.
55 // Blocks until the current work is cancelled.
56 void Cancel()
57 {
58 auto lg = GetLockGuard();
59
60 // Fast path avoids round trip thread communication and saves ~20us.
61 if (m_items.Empty())
62 return;
63
64 RunCommand([&] { m_items.Clear(); });
65 }
66
67 // Tells the worker thread to stop when its queue is empty.
68 // Blocks until the worker thread exits. Does nothing if thread isn't running.
69 void Shutdown()
70 {
71 auto lg = GetLockGuard();
72 WaitForCompletion();
73 StopThread();
74 }
75
76 // Tells the worker thread to stop immediately, potentially leaving work in the queue.
77 // Blocks until the worker thread exits. Does nothing if thread isn't running.
78 void Stop()
79 {
80 auto lg = GetLockGuard();
81 StopThread();
82 }
83
84 // Stops the worker thread ASAP and empties the queue.
85 void StopAndCancel()
86 {
87 auto lg = GetLockGuard();
88 Stop();
89 Cancel();
90 }
91
92 // Blocks until all items in the queue have been processed (or cancelled)
93 // Does nothing if thread isn't running.
94 void WaitForCompletion()
95 {
96 auto lg = GetLockGuard();
97 if (IsRunning())
98 m_items.WaitForEmpty();
99 }
100
101 bool IsRunning() { return m_thread.joinable(); }
102
103 private:
104 using CommandFunction = std::function<void()>;
105
106 // Blocking.
107 void RunCommand(CommandFunction cmd)
108 {
109 if (!IsRunning())
110 {
111 std::invoke(cmd);
112 return;
113 }
114
115 m_commands.Emplace(std::move(cmd));
116 m_event.Set();
117 m_commands.WaitForEmpty();
118 }
119
120 // Stop immediately.
121 void StopThread()
122 {
123 if (!m_thread.joinable())
124 return;
125
126 // empty-function shutdown signal.
127 m_commands.Emplace(CommandFunction{});
128 m_event.Set();
129 m_thread.join();
130 m_commands.Clear();
131 }
132
133 auto GetLockGuard()
134 {
135 struct DummyLockGuard
136 {
137 // Silences unused variable warning.
138 ~DummyLockGuard() { void(); }
139 };
140
141 if constexpr (IsSingleProducer)
142 return DummyLockGuard{};
143 else
144 return std::lock_guard{m_mutex};
145 }
146
147 void ThreadLoop(const std::string& thread_name, const FunctionType& function)
148 {
149 Common::SetCurrentThreadName(thread_name.c_str());
150
151 while (true)
152 {
153 while (!m_commands.Empty())
154 {
155 CommandFunction& command = m_commands.Front();
156 // empty-function shutdown signal.
157 if (!command)
158 return;
159
160 std::invoke(command);
161 m_commands.Pop();
162 }
163
164 if (m_items.Empty())
165 {
166 m_event.Wait();
167 continue;
168 }
169
170 function(std::move(m_items.Front()));
171 m_items.Pop();
172 }
173 }
174
175 std::thread m_thread;
176 Common::WaitableSPSCQueue<T> m_items;
177 Common::WaitableSPSCQueue<CommandFunction> m_commands;
178 Common::Event m_event;
179
180 using DummyMutex = std::type_identity<void>;
181 using ProducerMutex = std::conditional_t<IsSingleProducer, DummyMutex, std::recursive_mutex>;
182 ProducerMutex m_mutex;
183 };
184
185 // A WorkQueueThread-like class that takes functions to invoke.
186 template <template <typename> typename WorkThread>
187 class AsyncWorkThreadBase
188 {
189 public:
190 using FuncType = std::function<void()>;
191
192 AsyncWorkThreadBase() = default;
193 explicit AsyncWorkThreadBase(std::string thread_name) { Reset(std::move(thread_name)); }
194
195 void Reset(std::string thread_name)
196 {
197 m_worker.Reset(std::move(thread_name), std::invoke<FuncType>);
198 }
199
200 void Push(FuncType func) { m_worker.Push(std::move(func)); }
201
202 auto PushBlocking(FuncType func)
203 {
204 std::packaged_task task{std::move(func)};
205 m_worker.EmplaceItem([&] { task(); });
206 return task.get_future().get();
207 }
208
209 void Cancel() { m_worker.Cancel(); }
210 void Shutdown() { m_worker.Shutdown(); }
211 void WaitForCompletion() { m_worker.WaitForCompletion(); }
212
213 private:
214 WorkThread<FuncType> m_worker;
215 };
216 } // namespace detail
217
218 // Multiple threads may use the public interface.
219 template <typename T>
220 using WorkQueueThread = detail::WorkQueueThreadBase<T, false>;
221
222 // A "Single Producer" WorkQueueThread.
223 // It uses no mutex but only one thread can safely manipulate the queue.
224 template <typename T>
225 using WorkQueueThreadSP = detail::WorkQueueThreadBase<T, true>;
226
227 using AsyncWorkThread = detail::AsyncWorkThreadBase<WorkQueueThread>;
228 using AsyncWorkThreadSP = detail::AsyncWorkThreadBase<WorkQueueThreadSP>;
229
230 } // namespace Common