Qt
Internal/Contributor docs for the Qt SDK. Note: These are NOT official API docs; those are found at https://doc.qt.io/
Loading...
Searching...
No Matches
qfutureinterface.h
Go to the documentation of this file.
1// Copyright (C) 2020 The Qt Company Ltd.
2// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
3
4#ifndef QFUTUREINTERFACE_H
5#define QFUTUREINTERFACE_H
6
7#include <QtCore/qmutex.h>
8#include <QtCore/qresultstore.h>
9#include <QtCore/qtcoreexports.h>
10#ifndef QT_NO_EXCEPTIONS
11#include <exception>
12#endif
13
14#include <utility>
15
17
19QT_FORWARD_DECLARE_CLASS(QException)
20QT_BEGIN_NAMESPACE
21
22
23template <typename T> class QFuture;
24class QThreadPool;
25class QFutureInterfaceBase;
27class QFutureWatcherBase;
28class QFutureWatcherBasePrivate;
29
30namespace QtPrivate {
31template<typename Function, typename ResultType, typename ParentResultType>
33
34class ExceptionStore;
35
36template<class Function, class ResultType>
37class CanceledHandler;
38
39#ifndef QT_NO_EXCEPTIONS
40template<class Function, class ResultType>
41class FailureHandler;
42#endif
43
44#if QT_CORE_REMOVED_SINCE(6, 10)
48#endif // QT_CORE_REMOVED_SINCE(6, 10)
49}
50
51class Q_CORE_EXPORT QFutureInterfaceBase
52{
53public:
54 enum State {
55 NoState = 0x00,
56 Running = 0x01,
57 Started = 0x02,
58 Finished = 0x04,
59 Canceled = 0x08,
60 Suspending = 0x10,
61 Suspended = 0x20,
62 Throttled = 0x40,
63 // Pending means that the future depends on another one, which is not finished yet
64 Pending = 0x80,
65 };
66
67 QFutureInterfaceBase(State initialState = NoState);
68 QFutureInterfaceBase(const QFutureInterfaceBase &other);
69 QFutureInterfaceBase(QFutureInterfaceBase &&other) noexcept
70 : d(std::exchange(other.d, nullptr)) {}
71 QFutureInterfaceBase &operator=(const QFutureInterfaceBase &other);
72 QT_MOVE_ASSIGNMENT_OPERATOR_IMPL_VIA_MOVE_AND_SWAP(QFutureInterfaceBase)
73 virtual ~QFutureInterfaceBase();
74
75 // reporting functions available to the engine author:
76 void reportStarted();
77 void reportFinished();
78 void reportCanceled();
79#ifndef QT_NO_EXCEPTIONS
80 void reportException(const QException &e);
81#if QT_VERSION < QT_VERSION_CHECK(7, 0, 0)
82 void reportException(std::exception_ptr e);
83#else
84 void reportException(const std::exception_ptr &e);
85#endif
86#endif
87 void reportResultsReady(int beginIndex, int endIndex);
88
89 void setRunnable(QRunnable *runnable);
90 void setThreadPool(QThreadPool *pool);
91 QThreadPool *threadPool() const;
92 void setFilterMode(bool enable);
93 void setProgressRange(int minimum, int maximum);
94 int progressMinimum() const;
95 int progressMaximum() const;
96 bool isProgressUpdateNeeded() const;
97 void setProgressValue(int progressValue);
98 int progressValue() const;
99 void setProgressValueAndText(int progressValue, const QString &progressText);
100 QString progressText() const;
101
102 void setExpectedResultCount(int resultCount);
103 int expectedResultCount();
104 int resultCount() const;
105
106 bool queryState(State state) const;
107 bool isRunning() const;
108 bool isStarted() const;
109 bool isCanceled() const;
110 bool isFinished() const;
111#if QT_DEPRECATED_SINCE(6, 0)
112 QT_DEPRECATED_VERSION_X_6_0("Use isSuspending() or isSuspended() instead.")
113 bool isPaused() const;
114
115 QT_DEPRECATED_VERSION_X_6_0("Use setSuspended() instead.")
116 void setPaused(bool paused) { setSuspended(paused); }
117
118 QT_DEPRECATED_VERSION_X_6_0("Use toggleSuspended() instead.")
119 void togglePaused() { toggleSuspended(); }
120#endif
121 bool isSuspending() const;
122 bool isSuspended() const;
123 bool isThrottled() const;
124 bool isResultReadyAt(int index) const;
125 bool isValid() const;
126 int loadState() const;
127
128 void cancel();
129 void cancelAndFinish() { cancel(CancelMode::CancelAndFinish); }
130 void cancelChain();
131
132 void setSuspended(bool suspend);
133 void toggleSuspended();
134 void reportSuspended() const;
135 void setThrottled(bool enable);
136
137 void waitForFinished();
138 bool waitForNextResult();
139 void waitForResult(int resultIndex);
140 void waitForResume();
141 void suspendIfRequested();
142
143 QMutex &mutex() const;
144 bool hasException() const;
145 QtPrivate::ExceptionStore &exceptionStore();
146 QtPrivate::ResultStoreBase &resultStoreBase();
147 const QtPrivate::ResultStoreBase &resultStoreBase() const;
148
149 inline bool operator==(const QFutureInterfaceBase &other) const { return d == other.d; }
150 inline bool operator!=(const QFutureInterfaceBase &other) const { return d != other.d; }
151
152 // ### Qt 7: inline
153 void swap(QFutureInterfaceBase &other) noexcept;
154
155 template<typename T>
156 static QFutureInterfaceBase get(const QFuture<T> &future); // implemented in qfuture.h
157
158 bool isChainCanceled() const;
159
160protected:
161 // ### Qt 7: remove const from refT/derefT
162 bool refT() const noexcept;
163 bool derefT() const noexcept;
164 void reset();
165 void rethrowPossibleException();
166public:
167
168#ifndef QFUTURE_TEST
169private:
170#endif
171 friend class QFutureInterfaceBasePrivate;
172 QFutureInterfaceBasePrivate *d;
173
174private:
175 friend class QFutureWatcherBase;
176 friend class QFutureWatcherBasePrivate;
177
178 template<typename Function, typename ResultType, typename ParentResultType>
179 friend class QtPrivate::CompactContinuation;
180
181 template<class Function, class ResultType>
182 friend class QtPrivate::CanceledHandler;
183
184#ifndef QT_NO_EXCEPTIONS
185 template<class Function, class ResultType>
186 friend class QtPrivate::FailureHandler;
187#endif
188
189#if QT_CORE_REMOVED_SINCE(6, 10)
190 friend Q_CORE_EXPORT void QtPrivate::watchContinuationImpl(
191 const QObject *context, QtPrivate::QSlotObjectBase *slotObj, QFutureInterfaceBase &fi);
192#endif // QT_CORE_REMOVED_SINCE(6, 10)
193
194 template<class T>
195 friend class QPromise;
196
197protected:
198 enum class ContinuationType : quint8
199 {
200 Unknown,
201 Then,
202 OnFailed,
203 OnCanceled,
204 };
205
206#if QT_CORE_REMOVED_SINCE(6, 10)
207 void setContinuation(std::function<void(const QFutureInterfaceBase &)> func);
208 void setContinuation(std::function<void(const QFutureInterfaceBase &)> func,
209 QFutureInterfaceBasePrivate *continuationFutureData);
210#endif // QT_CORE_REMOVED_SINCE(6, 10)
211 void setContinuation(std::function<void(const QFutureInterfaceBase &)> func,
212 void *continuationFutureData, ContinuationType type);
213 void setContinuation(const QObject *context, std::function<void()> func,
214 const QVariant &continuationFuture, ContinuationType type);
215 void cleanContinuation();
216 void runContinuation() const;
217
218 void setLaunchAsync(bool value);
219 bool launchAsync() const;
220
221 bool isRunningOrPending() const;
222
223 enum class CancelMode { CancelOnly, CancelAndFinish };
224 void cancel(CancelMode mode);
225 void cancelChain(CancelMode mode);
226};
227
228inline void swap(QFutureInterfaceBase &lhs, QFutureInterfaceBase &rhs) noexcept
229{
230 lhs.swap(rhs);
231}
232
233template <typename T>
235{
236public:
237 QFutureInterface(State initialState = NoState)
238 : QFutureInterfaceBase(initialState)
239 {
240 refT();
241 }
243 : QFutureInterfaceBase(other)
244 {
245 refT();
246 }
247 QFutureInterface(const QFutureInterfaceBase &dd) : QFutureInterfaceBase(dd) { refT(); }
248 QFutureInterface(QFutureInterfaceBase &&dd) noexcept : QFutureInterfaceBase(std::move(dd)) { refT(); }
250 {
251 QFutureInterface copy(other);
252 swap(copy);
253 return *this;
254 }
257
259 {
260 if (!derefT() && !hasException())
261 resultStoreBase().template clear<T>();
262 }
263
266
267 inline QFuture<T> future(); // implemented in qfuture.h
268
269 template <typename...Args, std::enable_if_t<std::is_constructible_v<T, Args...>, bool> = true>
270 inline bool reportAndEmplaceResult(int index, Args&&...args);
271 inline bool reportResult(const T *result, int index = -1);
272 inline bool reportAndMoveResult(T &&result, int index = -1);
273 inline bool reportResult(T &&result, int index = -1);
274 inline bool reportResult(const T &result, int index = -1);
275 inline bool reportResults(const QList<T> &results, int beginIndex = -1, int count = -1);
276 inline bool reportFinished(const T *result);
278 {
279 QFutureInterfaceBase::reportFinished();
280 QFutureInterfaceBase::runContinuation();
281 }
282
283 inline const T &resultReference(int index) const;
284 inline const T *resultPointer(int index) const;
285 inline QList<T> results();
286
288#if 0
289 // TODO: Enable and make it return a QList, when QList is fixed to support move-only types
291#endif
292
293#ifndef QT_NO_EXCEPTIONS
294 void reportException(const std::exception_ptr &e)
295 {
296 if (hasException())
297 return;
298
299 resultStoreBase().template clear<T>();
300 QFutureInterfaceBase::reportException(e);
301 }
302 void reportException(const QException &e)
303 {
304 if (hasException())
305 return;
306
307 resultStoreBase().template clear<T>();
308 QFutureInterfaceBase::reportException(e);
309 }
310#endif
311};
312
313template <typename T>
314inline bool QFutureInterface<T>::reportResult(const T *result, int index)
315{
316 QMutexLocker<QMutex> locker{&mutex()};
317 if (this->queryState(Canceled) || this->queryState(Finished))
318 return false;
319
320 Q_ASSERT(!hasException());
321 QtPrivate::ResultStoreBase &store = resultStoreBase();
322
323 const int resultCountBefore = store.count();
324 const int insertIndex = store.addResult<T>(index, result);
325 if (insertIndex == -1)
326 return false;
327 if (store.filterMode()) {
328 this->reportResultsReady(resultCountBefore, store.count());
329 } else {
330 this->reportResultsReady(insertIndex, insertIndex + 1);
331 }
332 return true;
333}
334
335template<typename T>
336template<typename...Args, std::enable_if_t<std::is_constructible_v<T, Args...>, bool>>
337bool QFutureInterface<T>::reportAndEmplaceResult(int index, Args&&...args)
338{
339 QMutexLocker<QMutex> locker{&mutex()};
340 if (queryState(Canceled) || queryState(Finished))
341 return false;
342
343 Q_ASSERT(!hasException());
344 QtPrivate::ResultStoreBase &store = resultStoreBase();
345
346 const int oldResultCount = store.count();
347 const int insertIndex = store.emplaceResult<T>(index, std::forward<Args>(args)...);
348 // Let's make sure it's not in pending results.
349 if (insertIndex != -1 && (!store.filterMode() || oldResultCount < store.count()))
350 reportResultsReady(insertIndex, store.count());
351 return insertIndex != -1;
352}
353
354template<typename T>
355bool QFutureInterface<T>::reportAndMoveResult(T &&result, int index)
356{
357 return reportAndEmplaceResult(index, std::move(result));
358}
359
360template<typename T>
361bool QFutureInterface<T>::reportResult(T &&result, int index)
362{
363 return reportAndMoveResult(std::move(result), index);
364}
365
366template <typename T>
367inline bool QFutureInterface<T>::reportResult(const T &result, int index)
368{
369 return reportResult(&result, index);
370}
371
372template<typename T>
373inline bool QFutureInterface<T>::reportResults(const QList<T> &_results, int beginIndex, int count)
374{
375 QMutexLocker<QMutex> locker{&mutex()};
376 if (this->queryState(Canceled) || this->queryState(Finished))
377 return false;
378
379 Q_ASSERT(!hasException());
380 auto &store = resultStoreBase();
381
382 const int resultCountBefore = store.count();
383 const int insertIndex = store.addResults(beginIndex, &_results, count);
384 if (insertIndex == -1)
385 return false;
386 if (store.filterMode()) {
387 this->reportResultsReady(resultCountBefore, store.count());
388 } else {
389 this->reportResultsReady(insertIndex, insertIndex + _results.size());
390 }
391 return true;
392}
393
394template <typename T>
395inline bool QFutureInterface<T>::reportFinished(const T *result)
396{
397 bool resultReported = false;
398 if (result)
399 resultReported = reportResult(result);
400 reportFinished();
401 return resultReported;
402}
403
404template <typename T>
405inline const T &QFutureInterface<T>::resultReference(int index) const
406{
407 Q_ASSERT(!hasException());
408
409 QMutexLocker<QMutex> locker{&mutex()};
410 return resultStoreBase().resultAt(index).template value<T>();
411}
412
413template <typename T>
414inline const T *QFutureInterface<T>::resultPointer(int index) const
415{
416 Q_ASSERT(!hasException());
417
418 QMutexLocker<QMutex> locker{&mutex()};
419 return resultStoreBase().resultAt(index).template pointer<T>();
420}
421
422template <typename T>
424{
425 if (this->isCanceled()) {
426 rethrowPossibleException();
427 return QList<T>();
428 }
429
430 QFutureInterfaceBase::waitForResult(-1);
431
432 QList<T> res;
433 QMutexLocker<QMutex> locker{&mutex()};
434
435 QtPrivate::ResultIteratorBase it = resultStoreBase().begin();
436 while (it != resultStoreBase().end()) {
437 res.append(it.value<T>());
438 ++it;
439 }
440
441 return res;
442}
443
444template<typename T>
446{
447 Q_ASSERT(isValid());
448
449 // Note: we wait for all, this is intentional,
450 // not to mess with other unready results.
451 waitForResult(-1);
452
453 Q_ASSERT(!hasException());
454
455 const QMutexLocker<QMutex> locker{&mutex()};
456 QtPrivate::ResultIteratorBase position = resultStoreBase().resultAt(0);
457 T ret(std::move_if_noexcept(position.value<T>()));
458 reset();
459 resultStoreBase().template clear<T>();
460
461 return ret;
462}
463
464#if 0
465template<typename T>
466std::vector<T> QFutureInterface<T>::takeResults()
467{
468 Q_ASSERT(isValid());
469
470 waitForResult(-1);
471
472 Q_ASSERT(!hasException());
473
474 std::vector<T> res;
475 res.reserve(resultCount());
476
477 const QMutexLocker<QMutex> locker{&mutex()};
478
479 QtPrivate::ResultIteratorBase it = resultStoreBase().begin();
480 for (auto endIt = resultStoreBase().end(); it != endIt; ++it)
481 res.push_back(std::move_if_noexcept(it.value<T>()));
482
483 reset();
484 resultStoreBase().template clear<T>();
485
486 return res;
487}
488#endif
489
491QT_WARNING_DISABLE_CLANG("-Wweak-vtables") // QTBUG-125115
492
493template <>
494class QFutureInterface<void> : public QFutureInterfaceBase
495{
496public:
497 explicit QFutureInterface(State initialState = NoState)
498 : QFutureInterfaceBase(initialState)
499 { }
500
501 QFutureInterface(const QFutureInterfaceBase &dd) : QFutureInterfaceBase(dd) { }
502
503 static QFutureInterface<void> canceledResult()
504 { return QFutureInterface(State(Started | Finished | Canceled)); }
505
506
507 inline QFuture<void> future(); // implemented in qfuture.h
508
509 bool reportResult(const void *, int) { return false; }
510 bool reportResults(const QList<void> &, int) { return false; }
511 bool reportFinished(const void *)
512 {
513 reportFinished();
514 return false;
515 }
516 void reportFinished()
517 {
518 QFutureInterfaceBase::reportFinished();
519 QFutureInterfaceBase::runContinuation();
520 }
521};
522
523QT_WARNING_POP // Clang -Wweak-vtables
524
525template<typename T>
526inline void swap(QFutureInterface<T> &a, QFutureInterface<T> &b) noexcept
527{
528 a.swap(b);
529}
530
531QT_END_NAMESPACE
532
533#endif // QFUTUREINTERFACE_H
QFutureInterface(QFutureInterface &&other)=default
bool reportAndEmplaceResult(int index, Args &&...args)
QFutureInterface(const QFutureInterfaceBase &dd)
bool reportResult(T &&result, int index=-1)
QFutureInterface & operator=(const QFutureInterface &other)
bool reportResults(const QList< T > &results, int beginIndex=-1, int count=-1)
const T * resultPointer(int index) const
QFutureInterface(State initialState=NoState)
bool reportResult(const T &result, int index=-1)
void reportException(const std::exception_ptr &e)
QFutureInterface(const QFutureInterface &other)
bool reportFinished(const T *result)
void reportException(const QException &e)
bool reportResult(const T *result, int index=-1)
bool reportAndMoveResult(T &&result, int index=-1)
QFutureInterface(QFutureInterfaceBase &&dd) noexcept
const T & resultReference(int index) const
\inmodule QtCore
Definition qrunnable.h:18
void swap(QFutureInterfaceBase &lhs, QFutureInterfaceBase &rhs) noexcept
QFuture< void > future
[5]