Pyrogenesis HEAD
Pyrogenesis, a RTS Engine
Future.h
Go to the documentation of this file.
1/* Copyright (C) 2025 Wildfire Games.
2 * This file is part of 0 A.D.
3 *
4 * 0 A.D. is free software: you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License as published by
6 * the Free Software Foundation, either version 2 of the License, or
7 * (at your option) any later version.
8 *
9 * 0 A.D. is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
13 *
14 * You should have received a copy of the GNU General Public License
15 * along with 0 A.D. If not, see <http://www.gnu.org/licenses/>.
16 */
17
18#ifndef INCLUDED_FUTURE
19#define INCLUDED_FUTURE
20
21#include <atomic>
22#include <condition_variable>
23#include <exception>
24#include <memory>
25#include <mutex>
26#include <type_traits>
27#include <utility>
28#include <variant>
29
30template<typename Callback>
31class PackagedTask;
32
34{
35public:
36 explicit StopToken(const std::atomic<bool>& request) noexcept :
37 m_Request{request}
38 {}
39
40 bool IsStopRequested() const noexcept
41 {
42 return m_Request.load();
43 }
44private:
45 const std::atomic<bool>& m_Request;
46};
47
48template<typename Callback>
49using CallbackResult = typename std::conditional_t<std::is_invocable_v<Callback, StopToken>,
50 std::invoke_result<Callback, StopToken>, std::invoke_result<Callback>>::type;
51
53{
55template<typename ResultType>
56using NonVoid = std::conditional_t<std::is_void_v<ResultType>, VoidSubstitution, ResultType>;
57
58/**
59 * Responsible for syncronization between the task and the receiving thread.
60 */
61template<typename ResultType>
63{
64public:
65 Receiver() = default;
67 {
68 ENSURE(IsDone());
69 }
70
71 Receiver(const Receiver&) = delete;
72 Receiver(Receiver&&) = delete;
73
74 bool IsDone() const noexcept
75 {
76 return m_Done.load();
77 }
78
79 void Wait()
80 {
81 // Fast path: we're already done.
82 if (IsDone())
83 return;
84 // Slow path: we aren't done when we run the above check. Lock and wait until we are.
85 std::unique_lock<std::mutex> lock(m_Mutex);
86 m_ConditionVariable.wait(lock, [this]{ return IsDone(); });
87 }
88
89 /**
90 * Request the executing thread to stop as fast as possible. This is only
91 * a request the execution therad might ignore it.
92 * @see GetResult must not be called after a call to @p RequestStop.
93 */
94 void RequestStop() noexcept
95 {
96 m_StopRequest.store(true);
97 }
98
99 /**
100 * Move the result away from the shared state, mark the future invalid.
101 */
102 ResultType GetResult()
103 {
104 // The caller must ensure that this is only called if there is a result.
105 ENSURE(IsDone());
106 ENSURE(std::holds_alternative<NonVoid<ResultType>>(m_Outcome) ||
107 std::get<std::exception_ptr>(m_Outcome));
108
109 if (std::holds_alternative<std::exception_ptr>(m_Outcome))
110 std::rethrow_exception(std::exchange(std::get<std::exception_ptr>(m_Outcome), {}));
111
112 [[maybe_unused]] auto ret = std::move(std::get<NonVoid<ResultType>>(m_Outcome));
113 m_Outcome.template emplace<std::exception_ptr>();
114
115 if constexpr (std::is_void_v<ResultType>)
116 return;
117 else
118 return ret;
119 }
120
121 // This is only set by the executing thread and read by the receiving thread. It is never reset.
122 std::atomic<bool> m_Done{false};
123 // This is only set by the receiving thread and read by the executing thread. It is never reset.
124 std::atomic<bool> m_StopRequest{false};
125 std::mutex m_Mutex;
126 std::condition_variable m_ConditionVariable;
127
128 std::variant<std::exception_ptr, NonVoid<ResultType>> m_Outcome;
129};
130
131/**
132 * The shared state between futures and packaged state.
133 */
134template<typename Callback>
136{
137 SharedState(Callback&& callbackFunc) :
138 callback{std::forward<Callback>(callbackFunc)}
139 {}
140
141 Callback callback;
143};
144
145} // namespace FutureSharedStateDetail
146
147/**
148 * Corresponds somewhat to std::packaged_task.
149 * Like packaged_task, this holds a function acting as a promise.
150 * This type is mostly just the shared state and the call operator,
151 * handling the promise & continuation logic.
152 */
153template<typename Callback>
155{
156public:
157 PackagedTask() = delete;
159 m_SharedState(std::move(ss))
160 {}
161
163 {
164 if (!m_SharedState->receiver.m_StopRequest.load())
165 {
166 auto& outcome = m_SharedState->receiver.m_Outcome;
167 try
168 {
169 using ResultType = CallbackResult<Callback>;
170 if constexpr (std::is_void_v<ResultType>)
171 {
172 Invoke();
173 outcome.template emplace<FutureSharedStateDetail::VoidSubstitution>();
174 }
175 else
176 outcome.template emplace<ResultType>(Invoke());
177 }
178 catch(...)
179 {
180 outcome.template emplace<std::exception_ptr>(std::current_exception());
181 }
182 }
183
184 // Because we might have threads waiting on us, we need to make sure that they either:
185 // - don't wait on our condition variable
186 // - receive the notification when we're done.
187 // This requires locking the mutex (@see Wait).
188 {
189 std::lock_guard<std::mutex> lock(m_SharedState->receiver.m_Mutex);
190 m_SharedState->receiver.m_Done.store(true);
191 }
192
193 m_SharedState->receiver.m_ConditionVariable.notify_all();
194
195 // We no longer need the shared state, drop it immediately.
196 m_SharedState.reset();
197 }
198
199private:
201 {
202 if constexpr (std::is_invocable_v<Callback, StopToken>)
203 return m_SharedState->callback(StopToken{m_SharedState->receiver.m_StopRequest});
204 else
205 return m_SharedState->callback();
206 }
207
208 std::shared_ptr<FutureSharedStateDetail::SharedState<Callback>> m_SharedState;
209};
210
211/**
212 * Corresponds to std::future.
213 * Unlike std::future, Future can request the cancellation of the task that would produce the result.
214 * This makes it more similar to Java's CancellableTask or C#'s Task.
215 * The name Future was kept over Task so it would be more familiar to C++ users,
216 * but this all should be revised once Concurrency TS wraps up.
217 *
218 * Future is _not_ thread-safe. Call it from a single thread or ensure synchronization externally.
219 *
220 * The callback never runs after the @p Future is destroyed.
221 */
222template<typename ResultType>
224{
225 template<typename T>
226 friend class PackagedTask;
227
228public:
229 Future() = default;
230 Future(const Future& o) = delete;
231 Future(Future&&) = default;
233 {
234 CancelOrWait();
235 m_Receiver = std::move(other.m_Receiver);
236 return *this;
237 }
238
239 /**
240 * Make the future wait for the result of @a callback.
241 */
242 template<typename Callback, typename... Args>
243 Future(auto& taskManager, Callback&& callback, Args&&... args)
244 {
245 static_assert(std::is_same_v<CallbackResult<Callback>, ResultType>,
246 "The return type of the wrapped function is not the same as the type the Future expects.");
247 static_assert(std::is_invocable_v<Callback, StopToken> || !std::is_invocable_v<Callback, StopToken&>,
248 "Consider taking the `StopToken` by value");
249
250 auto temp = std::make_shared<FutureSharedStateDetail::SharedState<Callback>>(
251 std::forward<Callback>(callback));
252 m_Receiver = {temp, &temp->receiver};
253
254 taskManager.PushTask(PackagedTask<Callback>(std::move(temp)), std::forward<Args>(args)...);
255 }
256
258 {
259 CancelOrWait();
260 }
261
262 /**
263 * Move the result out of the future, and invalidate the future.
264 * If the future is not complete, calls Wait().
265 * If the future is invalid, asserts.
266 */
267 ResultType Get()
268 {
270
271 Wait();
272 // This mark the state invalid - can't call Get again.
273 return std::exchange(m_Receiver, nullptr)->GetResult();
274 }
275
276 /**
277 * @return true if the shared state is valid and has a result (i.e. Get can be called).
278 */
279 bool IsDone() const
280 {
281 return !!m_Receiver && m_Receiver->IsDone();
282 }
283
284 /**
285 * @return true if the future has a shared state and it's not been invalidated, ie. pending, started or done.
286 */
287 bool Valid() const
288 {
289 return !!m_Receiver;
290 }
291
292 void Wait()
293 {
294 if (Valid())
295 m_Receiver->Wait();
296 }
297
299 {
300 if (!Valid())
301 return;
302 m_Receiver->RequestStop();
303 m_Receiver->Wait();
304 m_Receiver.reset();
305 }
306
307protected:
308 std::shared_ptr<FutureSharedStateDetail::Receiver<ResultType>> m_Receiver;
309};
310
311template<typename Callback, typename... Args>
312Future(auto& taskManager, Callback&& callback, Args&&... args) -> Future<CallbackResult<Callback>>;
313
314#endif // INCLUDED_FUTURE
Future(auto &taskManager, Callback &&callback, Args &&... args) -> Future< CallbackResult< Callback > >
typename std::conditional_t< std::is_invocable_v< Callback, StopToken >, std::invoke_result< Callback, StopToken >, std::invoke_result< Callback > >::type CallbackResult
Definition: Future.h:50
Responsible for syncronization between the task and the receiving thread.
Definition: Future.h:63
std::condition_variable m_ConditionVariable
Definition: Future.h:126
std::atomic< bool > m_Done
Definition: Future.h:122
~Receiver()
Definition: Future.h:66
std::variant< std::exception_ptr, NonVoid< ResultType > > m_Outcome
Definition: Future.h:128
std::mutex m_Mutex
Definition: Future.h:125
Receiver(const Receiver &)=delete
void RequestStop() noexcept
Request the executing thread to stop as fast as possible.
Definition: Future.h:94
bool IsDone() const noexcept
Definition: Future.h:74
ResultType GetResult()
Move the result away from the shared state, mark the future invalid.
Definition: Future.h:102
std::atomic< bool > m_StopRequest
Definition: Future.h:124
void Wait()
Definition: Future.h:79
Corresponds to std::future.
Definition: Future.h:224
bool Valid() const
Definition: Future.h:287
ResultType Get()
Move the result out of the future, and invalidate the future.
Definition: Future.h:267
~Future()
Definition: Future.h:257
bool IsDone() const
Definition: Future.h:279
Future(Future &&)=default
Future & operator=(Future &&other)
Definition: Future.h:232
Future(auto &taskManager, Callback &&callback, Args &&... args)
Make the future wait for the result of callback.
Definition: Future.h:243
void Wait()
Definition: Future.h:292
Future()=default
void CancelOrWait()
Definition: Future.h:298
std::shared_ptr< FutureSharedStateDetail::Receiver< ResultType > > m_Receiver
Definition: Future.h:308
Future(const Future &o)=delete
Corresponds somewhat to std::packaged_task.
Definition: Future.h:155
PackagedTask()=delete
CallbackResult< Callback > Invoke()
Definition: Future.h:200
std::shared_ptr< FutureSharedStateDetail::SharedState< Callback > > m_SharedState
Definition: Future.h:208
void operator()()
Definition: Future.h:162
PackagedTask(std::shared_ptr< FutureSharedStateDetail::SharedState< Callback > > ss)
Definition: Future.h:158
Definition: Future.h:34
bool IsStopRequested() const noexcept
Definition: Future.h:40
const std::atomic< bool > & m_Request
Definition: Future.h:45
StopToken(const std::atomic< bool > &request) noexcept
Definition: Future.h:36
#define ENSURE(expr)
ensure the expression <expr> evaluates to non-zero.
Definition: debug.h:222
Definition: Future.h:53
std::conditional_t< std::is_void_v< ResultType >, VoidSubstitution, ResultType > NonVoid
Definition: Future.h:56
Definition: ShaderDefines.cpp:43
The shared state between futures and packaged state.
Definition: Future.h:136
Callback callback
Definition: Future.h:141
SharedState(Callback &&callbackFunc)
Definition: Future.h:137
Receiver< CallbackResult< Callback > > receiver
Definition: Future.h:142