File: Future.h

package info (click to toggle)
0ad 0.28.0-3
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 182,352 kB
  • sloc: cpp: 201,989; javascript: 19,730; ansic: 15,057; python: 6,597; sh: 2,046; perl: 1,232; xml: 543; java: 533; makefile: 105
file content (314 lines) | stat: -rw-r--r-- 8,432 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
/* Copyright (C) 2025 Wildfire Games.
 * This file is part of 0 A.D.
 *
 * 0 A.D. is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 2 of the License, or
 * (at your option) any later version.
 *
 * 0 A.D. is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with 0 A.D.  If not, see <http://www.gnu.org/licenses/>.
 */

#ifndef INCLUDED_FUTURE
#define INCLUDED_FUTURE

#include <atomic>
#include <condition_variable>
#include <exception>
#include <memory>
#include <mutex>
#include <type_traits>
#include <utility>
#include <variant>

template<typename Callback>
class PackagedTask;

class StopToken
{
public:
	explicit StopToken(const std::atomic<bool>& request) noexcept :
		m_Request{request}
	{}

	bool IsStopRequested() const noexcept
	{
		return m_Request.load();
	}
private:
	const std::atomic<bool>& m_Request;
};

template<typename Callback>
using CallbackResult = typename std::conditional_t<std::is_invocable_v<Callback, StopToken>,
	std::invoke_result<Callback, StopToken>, std::invoke_result<Callback>>::type;

namespace FutureSharedStateDetail
{
struct VoidSubstitution {};
template<typename ResultType>
using NonVoid = std::conditional_t<std::is_void_v<ResultType>, VoidSubstitution, ResultType>;

/**
 * Responsible for syncronization between the task and the receiving thread.
 */
template<typename ResultType>
class Receiver
{
public:
	Receiver() = default;
	~Receiver()
	{
		ENSURE(IsDone());
	}

	Receiver(const Receiver&) = delete;
	Receiver(Receiver&&) = delete;

	bool IsDone() const noexcept
	{
		return m_Done.load();
	}

	void Wait()
	{
		// Fast path: we're already done.
		if (IsDone())
			return;
		// Slow path: we aren't done when we run the above check. Lock and wait until we are.
		std::unique_lock<std::mutex> lock(m_Mutex);
		m_ConditionVariable.wait(lock, [this]{ return IsDone(); });
	}

	/**
	 * Request the executing thread to stop as fast as possible. This is only
	 * a request the execution therad might ignore it.
	 * @see GetResult must not be called after a call to @p RequestStop.
	 */
	void RequestStop() noexcept
	{
		m_StopRequest.store(true);
	}

	/**
	 * Move the result away from the shared state, mark the future invalid.
	 */
	ResultType GetResult()
	{
		// The caller must ensure that this is only called if there is a result.
		ENSURE(IsDone());
		ENSURE(std::holds_alternative<NonVoid<ResultType>>(m_Outcome) ||
			std::get<std::exception_ptr>(m_Outcome));

		if (std::holds_alternative<std::exception_ptr>(m_Outcome))
			std::rethrow_exception(std::exchange(std::get<std::exception_ptr>(m_Outcome), {}));

		[[maybe_unused]] auto ret = std::move(std::get<NonVoid<ResultType>>(m_Outcome));
		m_Outcome.template emplace<std::exception_ptr>();

		if constexpr (std::is_void_v<ResultType>)
			return;
		else
			return ret;
	}

	// This is only set by the executing thread and read by the receiving thread. It is never reset.
	std::atomic<bool> m_Done{false};
	// This is only set by the receiving thread and read by the executing thread. It is never reset.
	std::atomic<bool> m_StopRequest{false};
	std::mutex m_Mutex;
	std::condition_variable m_ConditionVariable;

	std::variant<std::exception_ptr, NonVoid<ResultType>> m_Outcome;
};

/**
 * The shared state between futures and packaged state.
 */
template<typename Callback>
struct SharedState
{
	SharedState(Callback&& callbackFunc) :
		callback{std::forward<Callback>(callbackFunc)}
	{}

	Callback callback;
	Receiver<CallbackResult<Callback>> receiver;
};

} // namespace FutureSharedStateDetail

/**
 * Corresponds somewhat to std::packaged_task.
 * Like packaged_task, this holds a function acting as a promise.
 * This type is mostly just the shared state and the call operator,
 * handling the promise & continuation logic.
 */
template<typename Callback>
class PackagedTask
{
public:
	PackagedTask() = delete;
	PackagedTask(std::shared_ptr<FutureSharedStateDetail::SharedState<Callback>> ss) :
		m_SharedState(std::move(ss))
	{}

	void operator()()
	{
		if (!m_SharedState->receiver.m_StopRequest.load())
		{
			auto& outcome = m_SharedState->receiver.m_Outcome;
			try
			{
				using ResultType = CallbackResult<Callback>;
				if constexpr (std::is_void_v<ResultType>)
				{
					Invoke();
					outcome.template emplace<FutureSharedStateDetail::VoidSubstitution>();
				}
				else
					outcome.template emplace<ResultType>(Invoke());
			}
			catch(...)
			{
				outcome.template emplace<std::exception_ptr>(std::current_exception());
			}
		}

		// Because we might have threads waiting on us, we need to make sure that they either:
		// - don't wait on our condition variable
		// - receive the notification when we're done.
		// This requires locking the mutex (@see Wait).
		{
			std::lock_guard<std::mutex> lock(m_SharedState->receiver.m_Mutex);
			m_SharedState->receiver.m_Done.store(true);
		}

		m_SharedState->receiver.m_ConditionVariable.notify_all();

		// We no longer need the shared state, drop it immediately.
		m_SharedState.reset();
	}

private:
	CallbackResult<Callback> Invoke()
	{
		if constexpr (std::is_invocable_v<Callback, StopToken>)
			return m_SharedState->callback(StopToken{m_SharedState->receiver.m_StopRequest});
		else
			return m_SharedState->callback();
	}

	std::shared_ptr<FutureSharedStateDetail::SharedState<Callback>> m_SharedState;
};

/**
 * Corresponds to std::future.
 * Unlike std::future, Future can request the cancellation of the task that would produce the result.
 * This makes it more similar to Java's CancellableTask or C#'s Task.
 * The name Future was kept over Task so it would be more familiar to C++ users,
 * but this all should be revised once Concurrency TS wraps up.
 *
 * Future is _not_ thread-safe. Call it from a single thread or ensure synchronization externally.
 *
 * The callback never runs after the @p Future is destroyed.
 */
template<typename ResultType>
class Future
{
	template<typename T>
	friend class PackagedTask;

public:
	Future() = default;
	Future(const Future& o) = delete;
	Future(Future&&) = default;
	Future& operator=(Future&& other)
	{
		CancelOrWait();
		m_Receiver = std::move(other.m_Receiver);
		return *this;
	}

	/**
	 * Make the future wait for the result of @a callback.
	 */
	template<typename Callback, typename... Args>
	Future(auto& taskManager, Callback&& callback, Args&&... args)
	{
		static_assert(std::is_same_v<CallbackResult<Callback>, ResultType>,
		"The return type of the wrapped function is not the same as the type the Future expects.");
		static_assert(std::is_invocable_v<Callback, StopToken> || !std::is_invocable_v<Callback, StopToken&>,
			"Consider taking the `StopToken` by value");

		auto temp = std::make_shared<FutureSharedStateDetail::SharedState<Callback>>(
			std::forward<Callback>(callback));
		m_Receiver = {temp, &temp->receiver};

		taskManager.PushTask(PackagedTask<Callback>(std::move(temp)), std::forward<Args>(args)...);
	}

	~Future()
	{
		CancelOrWait();
	}

	/**
	 * Move the result out of the future, and invalidate the future.
	 * If the future is not complete, calls Wait().
	 * If the future is invalid, asserts.
	 */
	ResultType Get()
	{
		ENSURE(!!m_Receiver);

		Wait();
		// This mark the state invalid - can't call Get again.
		return std::exchange(m_Receiver, nullptr)->GetResult();
	}

	/**
	 * @return true if the shared state is valid and has a result (i.e. Get can be called).
	 */
	bool IsDone() const
	{
		return !!m_Receiver && m_Receiver->IsDone();
	}

	/**
	 * @return true if the future has a shared state and it's not been invalidated, ie. pending, started or done.
	 */
	bool Valid() const
	{
		return !!m_Receiver;
	}

	void Wait()
	{
		if (Valid())
			m_Receiver->Wait();
	}

	void CancelOrWait()
	{
		if (!Valid())
			return;
		m_Receiver->RequestStop();
		m_Receiver->Wait();
		m_Receiver.reset();
	}

protected:
	std::shared_ptr<FutureSharedStateDetail::Receiver<ResultType>> m_Receiver;
};

template<typename Callback, typename... Args>
Future(auto& taskManager, Callback&& callback, Args&&... args) -> Future<CallbackResult<Callback>>;

#endif // INCLUDED_FUTURE