Line data Source code
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 : 30 : template<typename Callback> 31 : class PackagedTask; 32 : 33 : class StopToken 34 : { 35 : public: 36 10 : explicit StopToken(const std::atomic<bool>& request) noexcept : 37 8 : m_Request{request} 38 : {} 39 : 40 0 : bool IsStopRequested() const noexcept 41 : { 42 0 : return m_Request.load(); 43 : } 44 : private: 45 : const std::atomic<bool>& m_Request; 46 : }; 47 : 48 : template<typename Callback> 49 : using CallbackResult = typename std::conditional_t<std::is_invocable_v<Callback, StopToken>, 50 : std::invoke_result<Callback, StopToken>, std::invoke_result<Callback>>::type; 51 : 52 : namespace FutureSharedStateDetail 53 : { 54 : struct VoidSubstitution {}; 55 : template<typename ResultType> 56 : using 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 : */ 61 : template<typename ResultType> 62 : class Receiver 63 : { 64 : public: 65 201850 : Receiver() = default; 66 100928 : ~Receiver() 67 : { 68 100928 : ENSURE(IsDone()); 69 201856 : } 70 : 71 : Receiver(const Receiver&) = delete; 72 : Receiver(Receiver&&) = delete; 73 : 74 303331 : bool IsDone() const noexcept 75 : { 76 100928 : return m_Done.load(); 77 : } 78 : 79 100937 : void Wait() 80 : { 81 : // Fast path: we're already done. 82 100937 : if (IsDone()) 83 100666 : return; 84 : // Slow path: we aren't done when we run the above check. Lock and wait until we are. 85 271 : std::unique_lock<std::mutex> lock(m_Mutex); 86 811 : m_ConditionVariable.wait(lock, [this]{ return IsDone(); }); 87 271 : } 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 14 : void RequestStop() noexcept 95 : { 96 14 : m_StopRequest.store(true); 97 : } 98 : 99 : /** 100 : * Move the result away from the shared state, mark the future invalid. 101 : */ 102 100914 : ResultType GetResult() 103 : { 104 : // The caller must ensure that this is only called if there is a result. 105 100914 : ENSURE(IsDone()); 106 100914 : ENSURE(std::holds_alternative<NonVoid<ResultType>>(m_Outcome) || 107 : std::get<std::exception_ptr>(m_Outcome)); 108 : 109 100914 : if (std::holds_alternative<std::exception_ptr>(m_Outcome)) 110 6 : std::rethrow_exception(std::exchange(std::get<std::exception_ptr>(m_Outcome), {})); 111 : 112 100911 : [[maybe_unused]] auto ret = std::move(std::get<NonVoid<ResultType>>(m_Outcome)); 113 100911 : m_Outcome.template emplace<std::exception_ptr>(); 114 : 115 : if constexpr (std::is_void_v<ResultType>) 116 899 : return; 117 : else 118 100012 : 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 : */ 134 : template<typename Callback> 135 100926 : struct SharedState 136 : { 137 100928 : SharedState(Callback&& callbackFunc) : 138 100929 : callback{std::forward<Callback>(callbackFunc)} 139 2 : {} 140 : 141 : Callback callback; 142 : Receiver<CallbackResult<Callback>> receiver; 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 : */ 153 : template<typename Callback> 154 201856 : class PackagedTask 155 : { 156 : public: 157 : PackagedTask() = delete; 158 100928 : PackagedTask(std::shared_ptr<FutureSharedStateDetail::SharedState<Callback>> ss) : 159 34254 : m_SharedState(std::move(ss)) 160 : {} 161 : 162 100928 : void operator()() 163 : { 164 100928 : if (!m_SharedState->receiver.m_StopRequest.load()) 165 : { 166 100928 : 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 913 : Invoke(); 173 912 : outcome.template emplace<FutureSharedStateDetail::VoidSubstitution>(); 174 : } 175 : else 176 100025 : outcome.template emplace<ResultType>(Invoke()); 177 : } 178 3 : catch(...) 179 : { 180 3 : 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 100928 : std::lock_guard<std::mutex> lock(m_SharedState->receiver.m_Mutex); 190 100928 : m_SharedState->receiver.m_Done.store(true); 191 100927 : } 192 : 193 100927 : m_SharedState->receiver.m_ConditionVariable.notify_all(); 194 : 195 : // We no longer need the shared state, drop it immediately. 196 100927 : m_SharedState.reset(); 197 100926 : } 198 : 199 : private: 200 926 : CallbackResult<Callback> Invoke() 201 : { 202 : if constexpr (std::is_invocable_v<Callback, StopToken>) 203 2 : return m_SharedState->callback(StopToken{m_SharedState->receiver.m_StopRequest}); 204 : else 205 100926 : 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 : */ 222 : template<typename ResultType> 223 : class Future 224 : { 225 : template<typename T> 226 : friend class PackagedTask; 227 : 228 : public: 229 100024 : Future() = default; 230 : Future(const Future& o) = delete; 231 420 : Future(Future&&) = default; 232 100494 : Future& operator=(Future&& other) 233 : { 234 100494 : CancelOrWait(); 235 100494 : m_Receiver = std::move(other.m_Receiver); 236 100494 : return *this; 237 : } 238 : 239 : /** 240 : * Make the future wait for the result of @a callback. 241 : */ 242 : template<typename Callback, typename... Args> 243 100928 : Future(auto& taskManager, Callback&& callback, Args&&... args) 244 100928 : { 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 100928 : auto temp = std::make_shared<FutureSharedStateDetail::SharedState<Callback>>( 251 : std::forward<Callback>(callback)); 252 100928 : m_Receiver = {temp, &temp->receiver}; 253 : 254 201856 : taskManager.PushTask(PackagedTask<Callback>(std::move(temp)), std::forward<Args>(args)...); 255 100928 : } 256 : 257 201375 : ~Future() 258 : { 259 201375 : CancelOrWait(); 260 201375 : } 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 100914 : ResultType Get() 268 : { 269 100914 : ENSURE(!!m_Receiver); 270 : 271 100914 : Wait(); 272 : // This mark the state invalid - can't call Get again. 273 201825 : 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 12 : bool IsDone() const 280 : { 281 12 : 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 404903 : bool Valid() const 288 : { 289 403410 : return !!m_Receiver; 290 : } 291 : 292 100923 : void Wait() 293 : { 294 100923 : if (Valid()) 295 100923 : m_Receiver->Wait(); 296 : } 297 : 298 301869 : void CancelOrWait() 299 : { 300 301869 : if (!Valid()) 301 : return; 302 14 : m_Receiver->RequestStop(); 303 14 : m_Receiver->Wait(); 304 14 : m_Receiver.reset(); 305 : } 306 : 307 : protected: 308 : std::shared_ptr<FutureSharedStateDetail::Receiver<ResultType>> m_Receiver; 309 : }; 310 : 311 : template<typename Callback, typename... Args> 312 : Future(auto& taskManager, Callback&& callback, Args&&... args) -> Future<CallbackResult<Callback>>; 313 : 314 : #endif // INCLUDED_FUTURE