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
qfuture.qdoc
Go to the documentation of this file.
1// Copyright (C) 2016 The Qt Company Ltd.
2// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GFDL-1.3-no-invariants-only
3
4/*! \class QFuture
5 \inmodule QtCore
6 \threadsafe
7 \brief The QFuture class represents the result of an asynchronous computation.
8 \since 4.4
9
10 \ingroup thread
11
12 QFuture allows threads to be synchronized against one or more results
13 which will be ready at a later point in time. The result can be of any type
14 that has default, copy and possibly move constructors. If
15 a result is not available at the time of calling the result(), resultAt(),
16 results() and takeResult() functions, QFuture will wait until the result
17 becomes available. You can use the isResultReadyAt() function to determine
18 if a result is ready or not. For QFuture objects that report more than one
19 result, the resultCount() function returns the number of continuous results.
20 This means that it is always safe to iterate through the results from 0 to
21 resultCount(). takeResult() invalidates a future, and any subsequent attempt
22 to access result or results from the future leads to undefined behavior.
23 isValid() tells you if results can be accessed.
24
25 QFuture provides a \l{Java-style iterators}{Java-style iterator}
26 (QFutureIterator) and an \l{STL-style iterators}{STL-style iterator}
27 (QFuture::const_iterator). Using these iterators is another way to access
28 results in the future.
29
30 If the result of one asynchronous computation needs to be passed
31 to another, QFuture provides a convenient way of chaining multiple sequential
32 computations using then(). onCanceled() can be used for adding a handler to
33 be called if the QFuture is canceled. Additionally, onFailed() can be used
34 to handle any failures that occurred in the chain. Note that QFuture relies
35 on exceptions for the error handling. If using exceptions is not an option,
36 you can still indicate the error state of QFuture, by making the error type
37 part of the QFuture type. For example, you can use std::variant, std::any or
38 similar for keeping the result or failure or make your custom type.
39
40 The example below demonstrates how the error handling can be done without
41 using exceptions. Let's say we want to send a network request to obtain a large
42 file from a network location. Then we want to write it to the file system and
43 return its location in case of a success. Both of these operations may fail
44 with different errors. So, we use \c std::variant to keep the result
45 or error:
46
47 \snippet code/src_corelib_thread_qfuture.cpp 3
48
49 And we combine the two operations using then():
50
51 \snippet code/src_corelib_thread_qfuture.cpp 4
52
53 It's possible to chain multiple continuations and handlers in any order.
54 For example:
55
56 \snippet code/src_corelib_thread_qfuture.cpp 15
57
58 Depending on the state of \c testFuture (canceled, has exception or has a
59 result), the next onCanceled(), onFailed() or then() will be called. So
60 if \c testFuture is successfully fulfilled, \c {Block 1} will be called. If
61 it succeeds as well, the next then() (\c {Block 4}) is called. If \c testFuture
62 gets canceled or fails with an exception, either \c {Block 2} or \c {Block 3}
63 will be called respectively. The next then() will be called afterwards, and the
64 story repeats.
65
66 \note If \c {Block 2} is invoked and throws an exception, the following
67 onFailed() (\c {Block 3}) will handle it. If the order of onFailed() and
68 onCanceled() were reversed, the exception state would propagate to the
69 next continuations and eventually would be caught in \c {Block 5}.
70
71 In the next example the first onCanceled() (\c {Block 2}) is removed:
72
73 \snippet code/src_corelib_thread_qfuture.cpp 16
74
75 If \c testFuture gets canceled, its state is propagated to the next then(),
76 which will be also canceled. So in this case \c {Block 6} will be called.
77
78 The future can have only one continuation. Consider the following example:
79
80 \snippet code/src_corelib_thread_qfuture.cpp 31
81
82 In this case \c f1 and \c f2 are effectively the same QFuture object, as
83 they share the same internal state. As a result, calling
84 \l {QFuture::}{then} on \c f2 will overwrite the continuation specified for
85 \c {f1}. So, only \c {"second"} will be printed when this code is executed.
86
87 QFuture also offers ways to interact with a running computation. For
88 instance, the computation can be canceled with the cancel() function. To
89 suspend or resume the computation, use the setSuspended() function or one of
90 the suspend(), resume(), or toggleSuspended() convenience functions. Be aware
91 that not all running asynchronous computations can be canceled or suspended.
92 For example, the future returned by QtConcurrent::run() cannot be canceled;
93 but the future returned by QtConcurrent::mappedReduced() can.
94
95 Progress information is provided by the progressValue(),
96 progressMinimum(), progressMaximum(), and progressText() functions. The
97 waitForFinished() function causes the calling thread to block and wait for
98 the computation to finish, ensuring that all results are available.
99
100 The state of the computation represented by a QFuture can be queried using
101 the isCanceled(), isStarted(), isFinished(), isRunning(), isSuspending()
102 or isSuspended() functions.
103
104 QFuture<void> is specialized to not contain any of the result fetching
105 functions. Any QFuture<T> can be assigned or copied into a QFuture<void>
106 as well. This is useful if only status or progress information is needed
107 - not the actual result data.
108
109 To interact with running tasks using signals and slots, use QFutureWatcher.
110
111 You can also use QtFuture::connect() to connect signals to a QFuture object
112 which will be resolved when a signal is emitted. This allows working with
113 signals like with QFuture objects. For example, if you combine it with then(),
114 you can attach multiple continuations to a signal, which are invoked in the
115 same thread or a new thread.
116
117 The QtFuture::whenAll() and QtFuture::whenAny() functions can be used to
118 combine several futures and track when the last or first of them completes.
119
120 A ready QFuture object with a value or a QFuture object holding exception can
121 be created using convenience functions QtFuture::makeReadyVoidFuture(),
122 QtFuture::makeReadyValueFuture(), QtFuture::makeReadyRangeFuture(), and
123 QtFuture::makeExceptionalFuture().
124
125 \note Some APIs (see \l {QFuture::then()} or various QtConcurrent method
126 overloads) allow scheduling the computation to a specific thread pool.
127 However, QFuture implements a work-stealing algorithm to prevent deadlocks
128 and optimize thread usage. As a result, computations can be executed
129 directly in the thread which requests the QFuture's result.
130
131 \note To start a computation and store results in a QFuture, use QPromise or
132 one of the APIs in the \l {Qt Concurrent} framework.
133
134 \sa QPromise, QtFuture::connect(), QtFuture::makeReadyVoidFuture(),
135 QtFuture::makeReadyValueFuture(), QtFuture::makeReadyRangeFuture(),
136 QtFuture::makeExceptionalFuture(), QFutureWatcher, {Qt Concurrent}
137*/
138
139/*! \fn template <typename T> QFuture<T>::QFuture()
140
141 Constructs an empty, canceled future.
142*/
143
144/*! \fn template <typename T> QFuture<T>::QFuture(const QFuture<T> &other)
145
146 Constructs a copy of \a other.
147
148 \sa operator=()
149*/
150
151/*! \fn template <typename T> QFuture<T>::QFuture(QFutureInterface<T> *resultHolder)
152 \internal
153*/
154
155/*! \fn template <typename T> QFuture<T>::~QFuture()
156
157 Destroys the future.
158
159 Note that this neither waits nor cancels the asynchronous computation. Use
160 waitForFinished() or QFutureSynchronizer when you need to ensure that the
161 computation is completed before the future is destroyed.
162*/
163
164/*! \fn template <typename T> QFuture<T> &QFuture<T>::operator=(const QFuture<T> &other)
165
166 Assigns \a other to this future and returns a reference to this future.
167*/
168
169/*! \fn template <typename T> void QFuture<T>::cancel()
170
171 Cancels the asynchronous computation represented by this future. Note that
172 the cancellation is asynchronous. Use waitForFinished() after calling
173 cancel() when you need synchronous cancellation.
174
175 Results currently available may still be accessed on a canceled future,
176 but new results will \e not become available after calling this function.
177 Any QFutureWatcher object that is watching this future will not deliver
178 progress and result ready signals on a canceled future.
179
180 Be aware that not all running asynchronous computations can be canceled.
181 For example, the future returned by QtConcurrent::run() cannot be canceled;
182 but the future returned by QtConcurrent::mappedReduced() can.
183
184 \sa cancelChain()
185*/
186
187/*! \fn template <typename T> bool QFuture<T>::isCanceled() const
188
189 Returns \c true if the asynchronous computation has been canceled with the
190 cancel() function; otherwise returns \c false.
191
192 Be aware that the computation may still be running even though this
193 function returns \c true. See cancel() for more details.
194*/
195
196/*!
197 \fn template <typename T> void QFuture<T>::cancelChain()
198 \since 6.10
199
200 Cancels the entire continuation chain. All already-finished futures are
201 unchanged and their results are still available. Every pending continuation
202 is canceled, and its \l {onCanceled()} handler is called, if it exists in
203 the continuation chain.
204
205 \snippet code/src_corelib_thread_qfuture.cpp 38
206
207 In the example, if the chain is canceled before the \c {Then 2} continuation
208 is executed, both \c {OnCanceled 1} and \c {OnCanceled 2} cancellation
209 handlers will be invoked.
210
211 If the chain is canceled after \c {Then 2}, but before \c {Then 4}, then
212 only \c {OnCanceled 2} will be invoked.
213
214 \note When called on an already finished future, this method has no effect.
215 It's recommended to use it on the QFuture object that represents the entire
216 continuation chain, like it's shown in the example above.
217
218 \sa cancel()
219*/
220
221#if QT_DEPRECATED_SINCE(6, 0)
222/*! \fn template <typename T> void QFuture<T>::setPaused(bool paused)
223
224 \deprecated [6.0] Use setSuspended() instead.
225
226 If \a paused is true, this function pauses the asynchronous computation
227 represented by the future. If the computation is already paused, this
228 function does nothing. Any QFutureWatcher object that is watching this
229 future will stop delivering progress and result ready signals while the
230 future is paused. Signal delivery will continue once the future is
231 resumed.
232
233 If \a paused is false, this function resumes the asynchronous computation.
234 If the computation was not previously paused, this function does nothing.
235
236 Be aware that not all computations can be paused. For example, the future
237 returned by QtConcurrent::run() cannot be paused; but the future returned
238 by QtConcurrent::mappedReduced() can.
239
240 \sa suspend(), resume(), toggleSuspended()
241*/
242
243/*! \fn template <typename T> bool QFuture<T>::isPaused() const
244
245 \deprecated [6.0] Use isSuspending() or isSuspended() instead.
246
247 Returns \c true if the asynchronous computation has been paused with the
248 pause() function; otherwise returns \c false.
249
250 Be aware that the computation may still be running even though this
251 function returns \c true. See setPaused() for more details. To check
252 if pause actually took effect, use isSuspended() instead.
253
254 \sa toggleSuspended(), isSuspended()
255*/
256
257/*! \fn template <typename T> void QFuture<T>::pause()
258
259 \deprecated [6.0] Use suspend() instead.
260
261 Pauses the asynchronous computation represented by this future. This is a
262 convenience method that simply calls setPaused(true).
263
264 \sa resume()
265*/
266
267/*! \fn template <typename T> void QFuture<T>::togglePaused()
268
269 \deprecated [6.0] Use toggleSuspended() instead.
270
271 Toggles the paused state of the asynchronous computation. In other words,
272 if the computation is currently paused, calling this function resumes it;
273 if the computation is running, it is paused. This is a convenience method
274 for calling setPaused(!isPaused()).
275
276 \sa setSuspended(), suspend(), resume()
277*/
278#endif // QT_DEPRECATED_SINCE(6, 0)
279
280/*! \fn template <typename T> void QFuture<T>::setSuspended(bool suspend)
281
282 \since 6.0
283
284 If \a suspend is true, this function suspends the asynchronous computation
285 represented by the future(). If the computation is already suspended, this
286 function does nothing. QFutureWatcher will not immediately stop delivering
287 progress and result ready signals when the future is suspended. At the moment
288 of suspending there may still be computations that are in progress and cannot
289 be stopped. Signals for such computations will still be delivered.
290
291 If \a suspend is false, this function resumes the asynchronous computation.
292 If the computation was not previously suspended, this function does nothing.
293
294 Be aware that not all computations can be suspended. For example, the
295 QFuture returned by QtConcurrent::run() cannot be suspended; but the QFuture
296 returned by QtConcurrent::mappedReduced() can.
297
298 \sa suspend(), resume(), toggleSuspended()
299*/
300
301/*! \fn template <typename T> bool QFuture<T>::isSuspending() const
302
303 \since 6.0
304
305 Returns \c true if the asynchronous computation has been suspended with the
306 suspend() function, but the work is not yet suspended, and computation is still
307 running. Returns \c false otherwise.
308
309 To check if suspension is actually in effect, use isSuspended() instead.
310
311 \sa setSuspended(), toggleSuspended(), isSuspended()
312*/
313
314/*! \fn template <typename T> bool QFuture<T>::isSuspended() const
315
316 \since 6.0
317
318 Returns \c true if a suspension of the asynchronous computation has been
319 requested, and it is in effect, meaning that no more results or progress
320 changes are expected.
321
322 \sa setSuspended(), toggleSuspended(), isSuspending()
323*/
324
325/*! \fn template <typename T> void QFuture<T>::suspend()
326
327 \since 6.0
328
329 Suspends the asynchronous computation represented by this future. This is a
330 convenience method that simply calls setSuspended(true).
331
332 \sa resume()
333*/
334
335/*! \fn template <typename T> void QFuture<T>::resume()
336
337 Resumes the asynchronous computation represented by the future(). This is
338 a convenience method that simply calls setSuspended(false).
339
340 \sa suspend()
341*/
342
343/*! \fn template <typename T> void QFuture<T>::toggleSuspended()
344
345 \since 6.0
346
347 Toggles the suspended state of the asynchronous computation. In other words,
348 if the computation is currently suspending or suspended, calling this
349 function resumes it; if the computation is running, it is suspended. This is a
350 convenience method for calling setSuspended(!(isSuspending() || isSuspended())).
351
352 \sa setSuspended(), suspend(), resume()
353*/
354
355/*! \fn template <typename T> bool QFuture<T>::isStarted() const
356
357 Returns \c true if the asynchronous computation represented by this future
358 has been started; otherwise returns \c false.
359*/
360
361/*! \fn template <typename T> bool QFuture<T>::isFinished() const
362
363 Returns \c true if the asynchronous computation represented by this future
364 has finished; otherwise returns \c false.
365*/
366
367/*! \fn template <typename T> bool QFuture<T>::isRunning() const
368
369 Returns \c true if the asynchronous computation represented by this future is
370 currently running; otherwise returns \c false.
371*/
372
373/*! \fn template <typename T> int QFuture<T>::resultCount() const
374
375 Returns the number of continuous results available in this future. The real
376 number of results stored might be different from this value, due to gaps
377 in the result set. It is always safe to iterate through the results from 0
378 to resultCount().
379 \sa result(), resultAt(), results(), takeResult()
380*/
381
382/*! \fn template <typename T> int QFuture<T>::progressValue() const
383
384 Returns the current progress value, which is between the progressMinimum()
385 and progressMaximum().
386
387 \sa progressMinimum(), progressMaximum()
388*/
389
390/*! \fn template <typename T> int QFuture<T>::progressMinimum() const
391
392 Returns the minimum progressValue().
393
394 \sa progressValue(), progressMaximum()
395*/
396
397/*! \fn template <typename T> int QFuture<T>::progressMaximum() const
398
399 Returns the maximum progressValue().
400
401 \sa progressValue(), progressMinimum()
402*/
403
404/*! \fn template <typename T> QString QFuture<T>::progressText() const
405
406 Returns the (optional) textual representation of the progress as reported
407 by the asynchronous computation.
408
409 Be aware that not all computations provide a textual representation of the
410 progress, and as such, this function may return an empty string.
411*/
412
413/*! \fn template <typename T> void QFuture<T>::waitForFinished()
414
415 Waits for the asynchronous computation to finish (including cancel()ed
416 computations), i.e. until isFinished() returns \c true.
417*/
418
419/*! \fn template <typename T> template<typename U = T, typename = QtPrivate::EnableForNonVoid<U>> T QFuture<T>::result() const
420
421 Returns the first result in the future. If the result is not immediately
422 available, this function will block and wait for the result to become
423 available. This is a convenience method for calling resultAt(0). Note
424 that \c result() returns a copy of the internally stored result. If \c T is
425 a move-only type, or you don't want to copy the result, use takeResult()
426 instead.
427
428 \note Calling \c result() leads to undefined behavior if isValid()
429 returns \c false for this QFuture.
430
431 \sa resultAt(), results(), takeResult()
432*/
433
434/*! \fn template <typename T> template<typename U = T, typename = QtPrivate::EnableForNonVoid<U>> T QFuture<T>::resultAt(int index) const
435
436 Returns the result at \a index in the future. If the result is not
437 immediately available, this function will block and wait for the result to
438 become available.
439
440 \note Calling resultAt() leads to undefined behavior if isValid()
441 returns \c false for this QFuture.
442
443 \sa result(), results(), takeResult(), resultCount()
444*/
445
446/*! \fn template <typename T> template<typename U = T, typename = QtPrivate::EnableForNonVoid<U>> bool QFuture<T>::isResultReadyAt(int index) const
447
448 Returns \c true if the result at \a index is immediately available; otherwise
449 returns \c false.
450
451 \note Calling isResultReadyAt() leads to undefined behavior if isValid()
452 returns \c false for this QFuture.
453
454 \sa resultAt(), resultCount(), takeResult()
455*/
456
457/*! \fn template <typename T> template<typename U = T, typename = QtPrivate::EnableForNonVoid<U>> QList<T> QFuture<T>::results() const
458
459 Returns all results from the future. If the results are not immediately available,
460 this function will block and wait for them to become available. Note that
461 \c results() returns a copy of the internally stored results. Getting all
462 results of a move-only type \c T is not supported at the moment. However you can
463 still iterate through the list of move-only results by using \l{STL-style iterators}
464 or read-only \l{Java-style iterators}.
465
466 \note Calling \c results() leads to undefined behavior if isValid()
467 returns \c false for this QFuture.
468
469 \sa result(), resultAt(), takeResult(), resultCount(), isValid()
470*/
471
472#if 0
473/*! \fn template <typename T> template<typename U = T, typename = QtPrivate::EnableForNonVoid<U>> std::vector<T> QFuture<T>::takeResults()
474
475 If isValid() returns \c false, calling this function leads to undefined behavior.
476 takeResults() takes all results from the QFuture object and invalidates it
477 (isValid() will return \c false for this future). If the results are
478 not immediately available, this function will block and wait for them to
479 become available. This function tries to use move semantics for the results
480 if available and falls back to copy construction if the type is not movable.
481
482 \note QFuture in general allows sharing the results between different QFuture
483 objects (and potentially between different threads). takeResults() was introduced
484 to make QFuture also work with move-only types (like std::unique_ptr), so it
485 assumes that only one thread can move the results out of the future, and only
486 once.
487
488 \sa takeResult(), result(), resultAt(), results(), resultCount(), isValid()
489*/
490#endif
491
492/*! \fn template <typename T> template<typename U = T, typename = QtPrivate::EnableForNonVoid<U>> std::vector<T> QFuture<T>::takeResult()
493
494 \since 6.0
495
496 Call this function only if isValid() returns \c true, otherwise
497 the behavior is undefined. This function takes (moves) the first result from
498 the QFuture object, when only one result is expected. If there are any other
499 results, they are discarded after taking the first one.
500 If the result is not immediately available, this function will block and
501 wait for the result to become available. The QFuture will try to use move
502 semantics if possible, and will fall back to copy construction if the type
503 is not movable. After the result was taken, isValid() will evaluate
504 as \c false.
505
506 \note QFuture in general allows sharing the results between different QFuture
507 objects (and potentially between different threads). takeResult() was introduced
508 to make QFuture also work with move-only types (like std::unique_ptr), so it
509 assumes that only one thread can move the results out of the future, and
510 do it only once. Also note that taking the list of all results is not supported
511 at the moment. However you can still iterate through the list of move-only
512 results by using \l{STL-style iterators} or read-only \l{Java-style iterators}.
513
514 \sa result(), results(), resultAt(), isValid()
515*/
516
517/*! \fn template <typename T> bool QFuture<T>::isValid() const
518
519 \since 6.0
520
521 Returns \c true if a result or results can be accessed or taken from this
522 QFuture object. Returns false after the result was taken from the future.
523
524 \sa takeResult(), result(), results(), resultAt()
525*/
526
527/*! \fn template<typename T> template<class U = T, typename = QtPrivate::EnableForNonVoid<U>> QFuture<T>::const_iterator QFuture<T>::begin() const
528
529 Returns a const \l{STL-style iterators}{STL-style iterator} pointing to the first result in the
530 future.
531
532 \sa constBegin(), end()
533*/
534
535/*! \fn template<typename T> template<class U = T, typename = QtPrivate::EnableForNonVoid<U>> QFuture<T>::const_iterator QFuture<T>::end() const
536
537 Returns a const \l{STL-style iterators}{STL-style iterator} pointing to the imaginary result
538 after the last result in the future.
539
540 \sa begin(), constEnd()
541*/
542
543/*! \fn template<typename T> template<class U = T, typename = QtPrivate::EnableForNonVoid<U>> QFuture<T>::const_iterator QFuture<T>::constBegin() const
544
545 Returns a const \l{STL-style iterators}{STL-style iterator} pointing to the first result in the
546 future.
547
548 \sa begin(), constEnd()
549*/
550
551/*! \fn template<typename T> template<class U = T, typename = QtPrivate::EnableForNonVoid<U>> QFuture<T>::const_iterator QFuture<T>::constEnd() const
552
553 Returns a const \l{STL-style iterators}{STL-style iterator} pointing to the imaginary result
554 after the last result in the future.
555
556 \sa constBegin(), end()
557*/
558
559/*! \class QFuture::const_iterator
560 \reentrant
561 \since 4.4
562 \inmodule QtCore
563
564 \brief The QFuture::const_iterator class provides an STL-style const
565 iterator for QFuture.
566
567 QFuture provides both \l{STL-style iterators} and \l{Java-style iterators}.
568 The STL-style iterators are more low-level and more cumbersome to use; on
569 the other hand, they are slightly faster and, for developers who already
570 know STL, have the advantage of familiarity.
571
572 The default QFuture::const_iterator constructor creates an uninitialized
573 iterator. You must initialize it using a QFuture function like
574 QFuture::constBegin() or QFuture::constEnd() before you start iterating.
575 Here's a typical loop that prints all the results available in a future:
576
577 \snippet code/src_corelib_thread_qfuture.cpp 0
578
579 \sa QFutureIterator, QFuture
580*/
581
582/*! \typedef QFuture::const_iterator::iterator_category
583
584 Typedef for std::bidirectional_iterator_tag. Provided for STL compatibility.
585*/
586
587/*! \typedef QFuture::const_iterator::difference_type
588
589 Typedef for ptrdiff_t. Provided for STL compatibility.
590*/
591
592/*! \typedef QFuture::const_iterator::value_type
593
594 Typedef for T. Provided for STL compatibility.
595*/
596
597/*! \typedef QFuture::const_iterator::pointer
598
599 Typedef for const T *. Provided for STL compatibility.
600*/
601
602/*! \typedef QFuture::const_iterator::reference
603
604 Typedef for const T &. Provided for STL compatibility.
605*/
606
607/*! \fn template <typename T> QFuture<T>::const_iterator::const_iterator()
608
609 Constructs an uninitialized iterator.
610
611 Functions like operator*() and operator++() should not be called on an
612 uninitialized iterartor. Use operator=() to assign a value to it before
613 using it.
614
615 \sa QFuture::constBegin(), QFuture::constEnd()
616*/
617
618/*! \fn template <typename T> QFuture<T>::const_iterator::const_iterator(QFuture const * const future, int index)
619 \internal
620*/
621
622/*! \fn template <typename T> QFuture<T>::const_iterator::const_iterator(const const_iterator &other)
623
624 Constructs a copy of \a other.
625*/
626
627/*! \fn template <typename T> QFuture<T>::const_iterator &QFuture<T>::const_iterator::operator=(const const_iterator &other)
628
629 Assigns \a other to this iterator.
630*/
631
632/*! \fn template <typename T> const T &QFuture<T>::const_iterator::operator*() const
633
634 Returns the current result.
635*/
636
637/*! \fn template <typename T> const T *QFuture<T>::const_iterator::operator->() const
638
639 Returns a pointer to the current result.
640*/
641
642/*! \fn template <typename T> bool QFuture<T>::const_iterator::operator!=(const const_iterator &lhs, const const_iterator &rhs)
643
644 Returns \c true if \a lhs points to a different result than \a rhs iterator;
645 otherwise returns \c false.
646
647 \sa operator==()
648*/
649
650/*! \fn template <typename T> bool QFuture<T>::const_iterator::operator==(const const_iterator &lhs, const const_iterator &rhs)
651
652 Returns \c true if \a lhs points to the same result as \a rhs iterator;
653 otherwise returns \c false.
654
655 \sa operator!=()
656*/
657
658/*! \fn template <typename T> QFuture<T>::const_iterator &QFuture<T>::const_iterator::operator++()
659
660 The prefix \c{++} operator (\c{++it}) advances the iterator to the next result
661 in the future and returns an iterator to the new current result.
662
663 Calling this function on QFuture<T>::constEnd() leads to undefined results.
664
665 \sa operator--()
666*/
667
668/*! \fn template <typename T> QFuture<T>::const_iterator QFuture<T>::const_iterator::operator++(int)
669
670 \overload
671
672 The postfix \c{++} operator (\c{it++}) advances the iterator to the next
673 result in the future and returns an iterator to the previously current
674 result.
675*/
676
677/*! \fn template <typename T> QFuture<T>::const_iterator &QFuture<T>::const_iterator::operator--()
678
679 The prefix \c{--} operator (\c{--it}) makes the preceding result current and
680 returns an iterator to the new current result.
681
682 Calling this function on QFuture<T>::constBegin() leads to undefined results.
683
684 \sa operator++()
685*/
686
687/*! \fn template <typename T> QFuture<T>::const_iterator QFuture<T>::const_iterator::operator--(int)
688
689 \overload
690
691 The postfix \c{--} operator (\c{it--}) makes the preceding result current and
692 returns an iterator to the previously current result.
693*/
694
695/*! \fn template <typename T> QFuture<T>::const_iterator &QFuture<T>::const_iterator::operator+=(int j)
696
697 Advances the iterator by \a j results. (If \a j is negative, the iterator
698 goes backward.)
699
700 \sa operator-=(), operator+()
701*/
702
703/*! \fn template <typename T> QFuture<T>::const_iterator &QFuture<T>::const_iterator::operator-=(int j)
704
705 Makes the iterator go back by \a j results. (If \a j is negative, the
706 iterator goes forward.)
707
708 \sa operator+=(), operator-()
709*/
710
711/*! \fn template <typename T> QFuture<T>::const_iterator QFuture<T>::const_iterator::operator+(int j) const
712
713 Returns an iterator to the results at \a j positions forward from this
714 iterator. (If \a j is negative, the iterator goes backward.)
715
716 \sa operator-(), operator+=()
717*/
718
719/*! \fn template <typename T> QFuture<T>::const_iterator QFuture<T>::const_iterator::operator-(int j) const
720
721 Returns an iterator to the result at \a j positions backward from this
722 iterator. (If \a j is negative, the iterator goes forward.)
723
724 \sa operator+(), operator-=()
725*/
726
727/*! \typedef QFuture::ConstIterator
728
729 Qt-style synonym for QFuture::const_iterator.
730*/
731
732/*!
733 \class QFutureIterator
734 \reentrant
735 \since 4.4
736 \inmodule QtCore
737
738 \brief The QFutureIterator class provides a Java-style const iterator for
739 QFuture.
740
741 QFuture has both \l{Java-style iterators} and \l{STL-style iterators}. The
742 Java-style iterators are more high-level and easier to use than the
743 STL-style iterators; on the other hand, they are slightly less efficient.
744
745 An alternative to using iterators is to use index positions. Some QFuture
746 member functions take an index as their first parameter, making it
747 possible to access results without using iterators.
748
749 QFutureIterator<T> allows you to iterate over a QFuture<T>. Note that
750 there is no mutable iterator for QFuture (unlike the other Java-style
751 iterators).
752
753 The QFutureIterator constructor takes a QFuture as its argument. After
754 construction, the iterator is located at the very beginning of the result
755 list (i.e. before the first result). Here's how to iterate over all the
756 results sequentially:
757
758 \snippet code/src_corelib_thread_qfuture.cpp 1
759
760 The next() function returns the next result (waiting for it to become
761 available, if necessary) from the future and advances the iterator. Unlike
762 STL-style iterators, Java-style iterators point \e between results rather
763 than directly \e at results. The first call to next() advances the iterator
764 to the position between the first and second result, and returns the first
765 result; the second call to next() advances the iterator to the position
766 between the second and third result, and returns the second result; and
767 so on.
768
769 \image javaiterators1.png
770
771 Here's how to iterate over the elements in reverse order:
772
773 \snippet code/src_corelib_thread_qfuture.cpp 2
774
775 If you want to find all occurrences of a particular value, use findNext()
776 or findPrevious() in a loop.
777
778 Multiple iterators can be used on the same future. If the future is
779 modified while a QFutureIterator is active, the QFutureIterator will
780 continue iterating over the original future, ignoring the modified copy.
781
782 \sa QFuture::const_iterator, QFuture
783*/
784
785/*!
786 \fn template <typename T> QFutureIterator<T>::QFutureIterator(const QFuture<T> &future)
787
788 Constructs an iterator for traversing \a future. The iterator is set to be
789 at the front of the result list (before the first result).
790
791 \sa operator=()
792*/
793
794/*! \fn template <typename T> QFutureIterator<T> &QFutureIterator<T>::operator=(const QFuture<T> &future)
795
796 Makes the iterator operate on \a future. The iterator is set to be at the
797 front of the result list (before the first result).
798
799 \sa toFront(), toBack()
800*/
801
802/*! \fn template <typename T> void QFutureIterator<T>::toFront()
803
804 Moves the iterator to the front of the result list (before the first
805 result).
806
807 \sa toBack(), next()
808*/
809
810/*! \fn template <typename T> void QFutureIterator<T>::toBack()
811
812 Moves the iterator to the back of the result list (after the last result).
813
814 \sa toFront(), previous()
815*/
816
817/*! \fn template <typename T> bool QFutureIterator<T>::hasNext() const
818
819 Returns \c true if there is at least one result ahead of the iterator, e.g.,
820 the iterator is \e not at the back of the result list; otherwise returns
821 false.
822
823 \sa hasPrevious(), next()
824*/
825
826/*! \fn template <typename T> const T &QFutureIterator<T>::next()
827
828 Returns the next result and advances the iterator by one position.
829
830 Calling this function on an iterator located at the back of the result
831 list leads to undefined results.
832
833 \sa hasNext(), peekNext(), previous()
834*/
835
836/*! \fn template <typename T> const T &QFutureIterator<T>::peekNext() const
837
838 Returns the next result without moving the iterator.
839
840 Calling this function on an iterator located at the back of the result
841 list leads to undefined results.
842
843 \sa hasNext(), next(), peekPrevious()
844*/
845
846/*! \fn template <typename T> bool QFutureIterator<T>::hasPrevious() const
847
848 Returns \c true if there is at least one result ahead of the iterator, e.g.,
849 the iterator is \e not at the front of the result list; otherwise returns
850 false.
851
852 \sa hasNext(), previous()
853*/
854
855/*! \fn template <typename T> const T &QFutureIterator<T>::previous()
856
857 Returns the previous result and moves the iterator back by one position.
858
859 Calling this function on an iterator located at the front of the result
860 list leads to undefined results.
861
862 \sa hasPrevious(), peekPrevious(), next()
863*/
864
865/*! \fn template <typename T> const T &QFutureIterator<T>::peekPrevious() const
866
867 Returns the previous result without moving the iterator.
868
869 Calling this function on an iterator located at the front of the result
870 list leads to undefined results.
871
872 \sa hasPrevious(), previous(), peekNext()
873*/
874
875/*! \fn template <typename T> bool QFutureIterator<T>::findNext(const T &value)
876
877 Searches for \a value starting from the current iterator position forward.
878 Returns \c true if \a value is found; otherwise returns \c false.
879
880 After the call, if \a value was found, the iterator is positioned just
881 after the matching result; otherwise, the iterator is positioned at the
882 back of the result list.
883
884 \sa findPrevious()
885*/
886
887/*! \fn template <typename T> bool QFutureIterator<T>::findPrevious(const T &value)
888
889 Searches for \a value starting from the current iterator position
890 backward. Returns \c true if \a value is found; otherwise returns \c false.
891
892 After the call, if \a value was found, the iterator is positioned just
893 before the matching result; otherwise, the iterator is positioned at the
894 front of the result list.
895
896 \sa findNext()
897*/
898
899/*!
900 \namespace QtFuture
901 \inheaderfile QFuture
902
903 \inmodule QtCore
904 \brief Contains miscellaneous identifiers used by the QFuture class.
905*/
906
907
908/*!
909 \enum QtFuture::Launch
910
911 \since 6.0
912
913 Represents execution policies for running a QFuture continuation.
914
915 \value Sync The continuation will be launched in the same thread that
916 fulfills the promise associated with the future to which the
917 continuation was attached, or if it has already finished, the
918 continuation will be invoked immediately, in the thread that
919 executes \c then().
920
921 \value Async The continuation will be launched in a separate thread taken from
922 the global QThreadPool.
923
924 \value Inherit The continuation will inherit the launch policy or thread pool of
925 the future to which it is attached.
926
927 \c Sync is used as a default launch policy.
928
929 \sa QFuture::then(), QThreadPool::globalInstance()
930
931*/
932
933/*!
934 \class QtFuture::WhenAnyResult
935 \inmodule QtCore
936 \ingroup thread
937 \brief QtFuture::WhenAnyResult is used to represent the result of QtFuture::whenAny().
938 \since 6.3
939
940 The \c {QtFuture::WhenAnyResult<T>} struct is used for packaging the copy and
941 the index of the first completed \c QFuture<T> in the sequence of futures
942 packaging type \c T that are passed to QtFuture::whenAny().
943
944 \sa QFuture, QtFuture::whenAny()
945*/
946
947/*!
948 \variable QtFuture::WhenAnyResult::index
949
950 The field contains the index of the first completed QFuture in the sequence
951 of futures passed to whenAny(). It has type \c qsizetype.
952
953 \sa QtFuture::whenAny()
954*/
955
956/*!
957 \variable QtFuture::WhenAnyResult::future
958
959 The field contains the copy of the first completed QFuture that packages type
960 \c T, where \c T is the type packaged by the futures passed to whenAny().
961
962 \sa QtFuture::whenAny()
963*/
964
965/*! \fn template<class Sender, class Signal, typename = QtPrivate::EnableIfInvocable<Sender, Signal>> static QFuture<ArgsType<Signal>> QtFuture::connect(Sender *sender, Signal signal)
966
967 Creates and returns a QFuture which will become available when the \a sender emits
968 the \a signal. If the \a signal takes no arguments, a QFuture<void> is returned. If
969 the \a signal takes a single argument, the resulted QFuture will be filled with the
970 signal's argument value. If the \a signal takes multiple arguments, the resulted QFuture
971 is filled with std::tuple storing the values of signal's arguments. If the \a sender
972 is destroyed before the \a signal is emitted, the resulted QFuture will be canceled.
973
974 For example, let's say we have the following object:
975
976 \snippet code/src_corelib_thread_qfuture.cpp 10
977
978 We can connect its signals to QFuture objects in the following way:
979
980 \snippet code/src_corelib_thread_qfuture.cpp 11
981
982 We can also chain continuations to be run when a signal is emitted:
983
984 \snippet code/src_corelib_thread_qfuture.cpp 12
985
986 You can also start the continuation in a new thread or a custom thread pool
987 using QtFuture::Launch policies. For example:
988
989 \snippet code/src_corelib_thread_qfuture.cpp 13
990
991 Throwing an exception from a slot invoked by Qt's signal-slot connection
992 is considered to be an undefined behavior, if it is not handled within the
993 slot. But with QFuture::connect(), you can throw and handle exceptions from
994 the continuations:
995
996 \snippet code/src_corelib_thread_qfuture.cpp 14
997
998 \note The connected future will be fulfilled only once, when the signal is
999 emitted for the first time.
1000
1001 \sa QFuture, QFuture::then()
1002*/
1003
1004/*! \fn template<typename T, typename = QtPrivate::EnableForNonVoid<T>> static QFuture<std::decay_t<T>> QtFuture::makeReadyFuture(T &&value)
1005
1006 \since 6.1
1007 \overload
1008 \deprecated [6.6] Use makeReadyValueFuture() instead.
1009
1010 Creates and returns a QFuture which already has a result \a value.
1011 The returned QFuture has a type of std::decay_t<T>, where T is not void.
1012
1013 \code
1014 auto f = QtFuture::makeReadyFuture(std::make_unique<int>(42));
1015 ...
1016 const int result = *f.takeResult(); // result == 42
1017 \endcode
1018
1019 The method should be avoided because
1020 it has an inconsistent set of overloads. From Qt 6.10 onwards, using it
1021 in code will result in compiler warnings.
1022
1023 \sa QFuture, QtFuture::makeReadyVoidFuture(),
1024 QtFuture::makeReadyValueFuture(), QtFuture::makeReadyRangeFuture(),
1025 QtFuture::makeExceptionalFuture()
1026*/
1027
1028/*! \fn QFuture<void> QtFuture::makeReadyFuture()
1029
1030 \since 6.1
1031 \overload
1032 \deprecated [6.6] Use makeReadyVoidFuture() instead.
1033
1034 Creates and returns a void QFuture. Such QFuture can't store any result.
1035 One can use it to query the state of the computation.
1036 The returned QFuture will always be in the finished state.
1037
1038 \code
1039 auto f = QtFuture::makeReadyFuture();
1040 ...
1041 const bool started = f.isStarted(); // started == true
1042 const bool running = f.isRunning(); // running == false
1043 const bool finished = f.isFinished(); // finished == true
1044 \endcode
1045
1046 The method should be avoided because
1047 it has an inconsistent set of overloads. From Qt 6.10 onwards, using it
1048 in code will result in compiler warnings.
1049
1050 \sa QFuture, QFuture::isStarted(), QFuture::isRunning(),
1051 QFuture::isFinished(), QtFuture::makeReadyVoidFuture(),
1052 QtFuture::makeReadyValueFuture(), QtFuture::makeReadyRangeFuture(),
1053 QtFuture::makeExceptionalFuture()
1054*/
1055
1056/*! \fn template<typename T> static QFuture<T> QtFuture::makeReadyFuture(const QList<T> &values)
1057
1058 \since 6.1
1059 \overload
1060 \deprecated [6.6] Use makeReadyRangeFuture() instead.
1061
1062 Creates and returns a QFuture which already has multiple results set from \a values.
1063
1064 \code
1065 const QList<int> values { 1, 2, 3 };
1066 auto f = QtFuture::makeReadyFuture(values);
1067 ...
1068 const int count = f.resultCount(); // count == 3
1069 const auto results = f.results(); // results == { 1, 2, 3 }
1070 \endcode
1071
1072 The method should be avoided because
1073 it has an inconsistent set of overloads. From Qt 6.10 onwards, using it
1074 in code will result in compiler warnings.
1075
1076 \sa QFuture, QtFuture::makeReadyVoidFuture(),
1077 QtFuture::makeReadyValueFuture(), QtFuture::makeReadyRangeFuture(),
1078 QtFuture::makeExceptionalFuture()
1079*/
1080
1081/*! \fn template<typename T> static QFuture<std::decay_t<T>> QtFuture::makeReadyValueFuture(T &&value)
1082
1083 \since 6.6
1084
1085 Creates and returns a QFuture which already has a result \a value.
1086 The returned QFuture has a type of std::decay_t<T>, where T is not void.
1087 The returned QFuture will already be in the finished state.
1088
1089 \snippet code/src_corelib_thread_qfuture.cpp 35
1090
1091 \sa QFuture, QtFuture::makeReadyRangeFuture(),
1092 QtFuture::makeReadyVoidFuture(), QtFuture::makeExceptionalFuture()
1093*/
1094
1095/*! \fn QFuture<void> QtFuture::makeReadyVoidFuture()
1096
1097 \since 6.6
1098
1099 Creates and returns a void QFuture. Such QFuture can't store any result.
1100 One can use it to query the state of the computation.
1101 The returned QFuture will already be in the finished state.
1102
1103 \snippet code/src_corelib_thread_qfuture.cpp 36
1104
1105 \sa QFuture, QFuture::isStarted(), QFuture::isRunning(),
1106 QFuture::isFinished(), QtFuture::makeReadyValueFuture(),
1107 QtFuture::makeReadyRangeFuture(), QtFuture::makeExceptionalFuture()
1108*/
1109
1110/*! \fn template<typename T> static QFuture<T> QtFuture::makeExceptionalFuture(const QException &exception)
1111
1112 \since 6.1
1113
1114 Creates and returns a QFuture which already has an exception \a exception.
1115
1116 \code
1117 QException e;
1118 auto f = QtFuture::makeExceptionalFuture<int>(e);
1119 ...
1120 try {
1121 f.result(); // throws QException
1122 } catch (QException &) {
1123 // handle exception here
1124 }
1125 \endcode
1126
1127 \sa QFuture, QException, QtFuture::makeReadyVoidFuture(),
1128 QtFuture::makeReadyValueFuture()
1129*/
1130
1131/*! \fn template<typename T> static QFuture<T> QtFuture::makeExceptionalFuture(std::exception_ptr exception)
1132
1133 \since 6.1
1134 \overload
1135
1136 Creates and returns a QFuture which already has an exception \a exception.
1137
1138 \code
1139 struct TestException
1140 {
1141 };
1142 ...
1143 auto exception = std::make_exception_ptr(TestException());
1144 auto f = QtFuture::makeExceptionalFuture<int>(exception);
1145 ...
1146 try {
1147 f.result(); // throws TestException
1148 } catch (TestException &) {
1149 // handle exception here
1150 }
1151 \endcode
1152
1153 \sa QFuture, QException, QtFuture::makeReadyVoidFuture(),
1154 QtFuture::makeReadyValueFuture()
1155*/
1156
1157/*! \fn template<typename Container, QtFuture::if_container_with_input_iterators<Container>> static QFuture<QtFuture::ContainedType<Container>> QtFuture::makeReadyRangeFuture(Container &&container)
1158
1159 \since 6.6
1160 \overload
1161
1162 Takes an input container \a container and returns a QFuture with multiple
1163 results of type \c ContainedType initialized from the values of the
1164 \a container.
1165
1166 \snippet code/src_corelib_thread_qfuture.cpp 32
1167 \dots
1168 \snippet code/src_corelib_thread_qfuture.cpp 34
1169
1170 \constraints the \c Container has input iterators.
1171
1172 \sa QFuture, QtFuture::makeReadyVoidFuture(),
1173 QtFuture::makeReadyValueFuture(), QtFuture::makeExceptionalFuture()
1174*/
1175
1176/*! \fn template<typename ValueType> static QFuture<ValueType> QtFuture::makeReadyRangeFuture(std::initializer_list<ValueType> values)
1177
1178 \since 6.6
1179 \overload
1180
1181 Returns a QFuture with multiple results of type \c ValueType initialized
1182 from the input initializer list \a values.
1183
1184 \snippet code/src_corelib_thread_qfuture.cpp 33
1185 \dots
1186 \snippet code/src_corelib_thread_qfuture.cpp 34
1187
1188 \sa QFuture, QtFuture::makeReadyVoidFuture(),
1189 QtFuture::makeReadyValueFuture(), QtFuture::makeExceptionalFuture()
1190*/
1191
1192/*! \fn template<class T> template<class Function> QFuture<typename QFuture<T>::ResultType<Function>> QFuture<T>::then(Function &&function)
1193
1194 \since 6.0
1195 \overload
1196
1197 Attaches a continuation to this future, allowing to chain multiple asynchronous
1198 computations if desired, using the \l {QtFuture::Launch}{Sync} policy.
1199 \a function is a callable that takes an argument of the type packaged by this
1200 future if this has a result (is not a QFuture<void>). Otherwise it takes no
1201 arguments. This method returns a new QFuture that packages a value of the type
1202 returned by \a function. The returned future will be in an uninitialized state
1203 until the attached continuation is invoked, or until this future fails or is
1204 canceled.
1205
1206 \note Use other overloads of this method if you need to launch the continuation in
1207 a separate thread.
1208
1209 You can chain multiple operations like this:
1210
1211 \code
1212 QFuture<int> future = ...;
1213 future.then([](int res1){ ... }).then([](int res2){ ... })...
1214 \endcode
1215
1216 Or:
1217 \code
1218 QFuture<void> future = ...;
1219 future.then([](){ ... }).then([](){ ... })...
1220 \endcode
1221
1222 The continuation can also take a QFuture argument (instead of its value), representing
1223 the previous future. This can be useful if, for example, QFuture has multiple results,
1224 and the user wants to access them inside the continuation. Or the user needs to handle
1225 the exception of the previous future inside the continuation, to not interrupt the chain
1226 of multiple continuations. For example:
1227
1228 \snippet code/src_corelib_thread_qfuture.cpp 5
1229
1230 If the previous future throws an exception and it is not handled inside the
1231 continuation, the exception will be propagated to the continuation future, to
1232 allow the caller to handle it:
1233
1234 \snippet code/src_corelib_thread_qfuture.cpp 6
1235
1236 In this case the whole chain of continuations will be interrupted.
1237
1238 \note If this future gets canceled, the continuations attached to it will
1239 also be canceled.
1240
1241 \sa onFailed(), onCanceled()
1242*/
1243
1244/*! \fn template<class T> template<class Function> QFuture<typename QFuture<T>::ResultType<Function>> QFuture<T>::then(QtFuture::Launch policy, Function &&function)
1245
1246 \since 6.0
1247 \overload
1248
1249 Attaches a continuation to this future, allowing to chain multiple asynchronous
1250 computations. When the asynchronous computation represented by this future
1251 finishes, \a function will be invoked according to the given launch \a policy.
1252 A new QFuture representing the result of the continuation is returned.
1253
1254 Depending on the \a policy, continuation will be invoked in the same thread as
1255 this future, in a new thread, or will inherit the launch policy and thread pool of
1256 this future. If no launch policy is specified (see the overload taking only a callable),
1257 the \c Sync policy will be used.
1258
1259 In the following example both continuations will be invoked in a new thread (but in
1260 the same one).
1261
1262 \code
1263 QFuture<int> future = ...;
1264 future.then(QtFuture::Launch::Async, [](int res){ ... }).then([](int res2){ ... });
1265 \endcode
1266
1267 In the following example both continuations will be invoked in new threads using the
1268 same thread pool.
1269
1270 \code
1271 QFuture<int> future = ...;
1272 future.then(QtFuture::Launch::Async, [](int res){ ... })
1273 .then(QtFuture::Launch::Inherit, [](int res2){ ... });
1274 \endcode
1275
1276 See the documentation of the other overload for more details about \a function.
1277
1278 \sa onFailed(), onCanceled()
1279*/
1280
1281/*! \fn template<class T> template<class Function> QFuture<typename QFuture<T>::ResultType<Function>> QFuture<T>::then(QThreadPool *pool, Function &&function)
1282
1283 \since 6.0
1284 \overload
1285
1286 Attaches a continuation to this future, allowing to chain multiple asynchronous
1287 computations if desired. When the asynchronous computation represented by this
1288 future finishes, \a function will be scheduled on \a pool.
1289
1290 \sa onFailed(), onCanceled()
1291*/
1292
1293/*! \fn template<class T> template<class Function> QFuture<typename QFuture<T>::ResultType<Function>> QFuture<T>::then(QObject *context, Function &&function)
1294
1295 \since 6.1
1296 \overload
1297
1298 Attaches a continuation to this future, allowing to chain multiple asynchronous
1299 computations if desired. When the asynchronous computation represented by this
1300 future finishes, \a function will be invoked in the thread of the \a context object.
1301 This can be useful if the continuation needs to be invoked in a specific thread.
1302 For example:
1303
1304 \snippet code/src_corelib_thread_qfuture.cpp 17
1305
1306 The continuation attached into QtConcurrent::run updates the UI elements and cannot
1307 be invoked from a non-gui thread. So \c this is provided as a context to \c .then(),
1308 to make sure that it will be invoked in the main thread.
1309
1310 The following continuations will be also invoked from the same context,
1311 unless a different context or launch policy is specified:
1312
1313 \snippet code/src_corelib_thread_qfuture.cpp 18
1314
1315 This is because by default \c .then() is invoked from the same thread as the
1316 previous one.
1317
1318 But note that if the continuation is attached after this future has already finished,
1319 it will be invoked immediately, in the thread that executes \c then():
1320
1321 \snippet code/src_corelib_thread_qfuture.cpp 20
1322
1323 In the above example if \c cachedResultsReady is \c true, and a ready future is
1324 returned, it is possible that the first \c .then() finishes before the second one
1325 is attached. In this case it will be resolved in the current thread. Therefore, when
1326 in doubt, pass the context explicitly.
1327
1328 \target context_lifetime
1329 If the \a context is destroyed before the chain has finished, the future is canceled.
1330 This implies that a cancellation handler might be invoked when the \a context is not valid
1331 anymore. To guard against this, capture the \a context as a QPointer:
1332
1333 \snippet code/src_corelib_thread_qfuture.cpp 37
1334
1335 When the context object is destroyed, cancellation happens immediately. Previous futures in the
1336 chain are \e {not} cancelled and keep running until they are finished.
1337
1338 \note When calling this method, it should be guaranteed that the \a context stays alive
1339 during setup of the chain.
1340
1341 \sa onFailed(), onCanceled()
1342*/
1343
1344/*! \fn template<class T> template<class Function, typename = std::enable_if_t<!QtPrivate::ArgResolver<Function>::HasExtraArgs>> QFuture<T> QFuture<T>::onFailed(Function &&handler)
1345
1346 \since 6.0
1347
1348 Attaches a failure handler to this future, to handle any exceptions. The
1349 returned future behaves exactly as this future (has the same state and result)
1350 unless this future fails with an exception.
1351
1352 The \a handler is a callable which takes either no argument or one argument, to
1353 filter by specific error types, similar to the
1354 \l {https://en.cppreference.com/w/cpp/language/try_catch} {catch} statement.
1355 It returns a value of the type packaged by this future. After the failure, the
1356 returned future packages the value returned by \a handler.
1357
1358 The handler will only be invoked if an exception is raised. If the exception
1359 is raised after this handler is attached, the handler is executed in the thread
1360 that reports the future as finished as a result of the exception. If the handler
1361 is attached after this future has already failed, it will be invoked immediately,
1362 in the thread that executes \c onFailed(). Therefore, the handler cannot always
1363 make assumptions about which thread it will be run on. Use the overload that
1364 takes a context object if you want to control which thread the handler is
1365 invoked on.
1366
1367 The example below demonstrates how to attach a failure handler:
1368
1369 \snippet code/src_corelib_thread_qfuture.cpp 7
1370
1371 If there are multiple handlers attached, the first handler that matches with the
1372 thrown exception type will be invoked. For example:
1373
1374 \snippet code/src_corelib_thread_qfuture.cpp 8
1375
1376 If none of the handlers matches with the thrown exception type, the exception
1377 will be propagated to the resulted future:
1378
1379 \snippet code/src_corelib_thread_qfuture.cpp 9
1380
1381 \note You can always attach a handler taking no argument, to handle all exception
1382 types and avoid writing the try-catch block.
1383
1384 \sa then(), onCanceled()
1385*/
1386
1387/*! \fn template<class T> template<class Function, typename = std::enable_if_t<!QtPrivate::ArgResolver<Function>::HasExtraArgs>> QFuture<T> QFuture<T>::onFailed(QObject *context, Function &&handler)
1388
1389 \since 6.1
1390 \overload
1391
1392 Attaches a failure handler to this future, to handle any exceptions that the future
1393 raises, or that it has already raised. Returns a QFuture of the same type as this
1394 future. The handler will be invoked only in case of an exception, in the thread of
1395 the \a context object. This can be useful if the failure needs to be handled in a
1396 specific thread. For example:
1397
1398 \snippet code/src_corelib_thread_qfuture.cpp 19
1399
1400 The failure handler attached into QtConcurrent::run updates the UI elements and cannot
1401 be invoked from a non-gui thread. So \c this is provided as a context to \c .onFailed(),
1402 to make sure that it will be invoked in the main thread.
1403
1404 If the \a context is destroyed before the chain has finished, the future is canceled.
1405 See \l {context_lifetime}{then()} for details.
1406
1407 \note When calling this method, it should be guaranteed that the \a context stays alive
1408 during setup of the chain.
1409
1410 See the documentation of the other overload for more details about \a handler.
1411
1412 \sa then(), onCanceled()
1413*/
1414
1415/*! \fn template<class T> template<class Function, typename = std::enable_if_t<std::is_invocable_r_v<T, Function>>> QFuture<T> QFuture<T>::onCanceled(Function &&handler)
1416
1417 \since 6.0
1418
1419 Attaches a cancellation \a handler to this future. The returned future
1420 behaves exactly as this future (has the same state and result) unless
1421 this future is cancelled. The \a handler is a callable which takes no
1422 arguments and returns a value of the type packaged by this future. After
1423 cancellation, the returned future packages the value returned by \a handler.
1424
1425 If attached before the cancellation, \a handler will be invoked in the same
1426 thread that reports the future as finished after the cancellation. If the
1427 handler is attached after this future has already been canceled, it will be
1428 invoked immediately in the thread that executes \c onCanceled(). Therefore,
1429 the handler cannot always make assumptions about which thread it will be run
1430 on. Use the overload that takes a context object if you want to control
1431 which thread the handler is invoked on.
1432
1433 The example below demonstrates how to attach a cancellation handler:
1434
1435 \snippet code/src_corelib_thread_qfuture.cpp 21
1436
1437 If \c testFuture is canceled, \c {Block 3} will be called and the
1438 \c resultFuture will have \c -1 as its result. Unlike \c testFuture, it won't
1439 be in a \c Canceled state. This means that you can get its result, attach
1440 countinuations to it, and so on.
1441
1442 Also note that you can cancel the chain of continuations while they are
1443 executing via the future that started the chain. Let's say \c testFuture.cancel()
1444 was called while \c {Block 1} is already executing. The next continuation will
1445 detect that cancellation was requested, so \c {Block 2} will be skipped, and
1446 the cancellation handler (\c {Block 3}) will be called.
1447
1448 \note This method returns a new \c QFuture representing the result of the
1449 continuation chain. Canceling the resulting \c QFuture itself won't invoke the
1450 cancellation handler in the chain that lead to it. This means that if you call
1451 \c resultFuture.cancel(), \c {Block 3} won't be called: because \c resultFuture is
1452 the future that results from attaching the cancellation handler to \c testFuture,
1453 no cancellation handlers have been attached to \c resultFuture itself. Only
1454 cancellation of \c testFuture or the futures returned by continuations attached
1455 before the \c onCancelled() call can trigger \c{Block 3}.
1456
1457 \sa then(), onFailed()
1458*/
1459
1460/*! \fn template<class T> template<class Function, typename = std::enable_if_t<std::is_invocable_r_v<T, Function>>> QFuture<T> QFuture<T>::onCanceled(QObject *context, Function &&handler)
1461
1462 \since 6.1
1463 \overload
1464
1465 Attaches a cancellation \a handler to this future, to be called when the future is
1466 canceled. The \a handler is a callable which doesn't take any arguments. It will be
1467 invoked in the thread of the \a context object. This can be useful if the cancellation
1468 needs to be handled in a specific thread.
1469
1470 If the \a context is destroyed before the chain has finished, the future is canceled.
1471 See \l {context_lifetime}{then()} for details.
1472
1473 \note When calling this method, it should be guaranteed that the \a context stays alive
1474 during setup of the chain.
1475
1476 See the documentation of the other overload for more details about \a handler.
1477
1478 \sa then(), onFailed()
1479*/
1480
1481/*! \fn template<class T> template<class U> QFuture<U> QFuture<T>::unwrap()
1482
1483 \since 6.4
1484
1485 Unwraps the inner future from this \c QFuture<T>, where \c T is a future
1486 of type \c QFuture<U>, i.e. this future has type of \c QFuture<QFuture<U>>.
1487 For example:
1488
1489 \snippet code/src_corelib_thread_qfuture.cpp 28
1490
1491 \c unwrappedFuture will be fulfilled as soon as the inner future nested
1492 inside the \c outerFuture is fulfilled, with the same result or exception
1493 and in the same thread that reports the inner future as finished. If the
1494 inner future is canceled, \c unwrappedFuture will also be canceled.
1495
1496 This is especially useful when chaining multiple computations, and one of
1497 them returns a \c QFuture as its result type. For example, let's say we
1498 want to download multiple images from an URL, scale the images, and reduce
1499 them to a single image using QtConcurrent::mappedReduced(). We could write
1500 something like:
1501
1502 \snippet code/src_corelib_thread_qfuture.cpp 29
1503
1504 Here \c QtConcurrent::mappedReduced() returns a \c QFuture<QImage>, so
1505 \c .then(processImages) returns a \c QFuture<QFuture<QImage>>. Since
1506 \c show() takes a \c QImage as argument, the result of \c .then(processImages)
1507 can't be passed to it directly. We need to call \c .unwrap(), that will
1508 get the result of the inner future when it's ready and pass it to the next
1509 continuation.
1510
1511 In case of multiple nesting, \c .unwrap() goes down to the innermost level:
1512
1513 \snippet code/src_corelib_thread_qfuture.cpp 30
1514*/
1515
1516/*! \fn template<typename OutputSequence, typename InputIt> QFuture<OutputSequence> QtFuture::whenAll(InputIt first, InputIt last)
1517
1518 \since 6.3
1519
1520 Returns a new QFuture that succeeds when all futures from \a first to \a last
1521 complete. \a first and \a last are iterators to a sequence of futures packaging
1522 type \c T. \c OutputSequence is a sequence containing all completed futures
1523 from \a first to \a last, appearing in the same order as in the input. If the
1524 type of \c OutputSequence is not specified, the resulting futures will be
1525 returned in a \c QList of \c QFuture<T>. For example:
1526
1527 \snippet code/src_corelib_thread_qfuture.cpp 22
1528
1529 \note The output sequence must support random access and the \c resize()
1530 operation.
1531
1532 If \c first equals \c last, this function returns a ready QFuture that
1533 contains an empty \c OutputSequence.
1534
1535//! [whenAll]
1536 The returned future always completes successfully after all the specified
1537 futures complete. It doesn't matter if any of these futures completes with
1538 error or is canceled. You can use \c .then() to process the completed futures
1539 after the future returned by \c whenAll() succeeds:
1540//! [whenAll]
1541
1542 \snippet code/src_corelib_thread_qfuture.cpp 23
1543
1544//! [whenAll-note]
1545 \note If the input futures complete on different threads, the future returned
1546 by this method will complete in the thread that the last future completes in.
1547 Therefore, the continuations attached to the future returned by \c whenAll()
1548 cannot always make assumptions about which thread they will be run on. Use the
1549 overload of \c .then() that takes a context object if you want to control which
1550 thread the continuations are invoked on.
1551//! [whenAll-note]
1552*/
1553
1554/*! \fn template<typename OutputSequence, typename... Futures> QFuture<OutputSequence> QtFuture::whenAll(Futures &&... futures)
1555
1556 \since 6.3
1557
1558 Returns a new QFuture that succeeds when all \a futures packaging arbitrary
1559 types complete. \c OutputSequence is a sequence of completed futures. The type
1560 of its entries is \c std::variant<Futures...>. For each \c QFuture<T> passed to
1561 \c whenAll(), the entry at the corresponding position in \c OutputSequence
1562 will be a \c std::variant holding that \c QFuture<T>, in its completed state.
1563 If the type of \c OutputSequence is not specified, the resulting futures will
1564 be returned in a QList of \c std::variant<Futures...>. For example:
1565
1566 \snippet code/src_corelib_thread_qfuture.cpp 24
1567
1568 \note The output sequence should support random access and the \c resize()
1569 operation.
1570
1571 \include qfuture.qdoc whenAll
1572
1573 \snippet code/src_corelib_thread_qfuture.cpp 25
1574
1575 \include qfuture.qdoc whenAll-note
1576*/
1577
1578/*! \fn template<typename T, typename InputIt> QFuture<QtFuture::WhenAnyResult<T>> QtFuture::whenAny(InputIt first, InputIt last)
1579
1580 \since 6.3
1581
1582 Returns a new QFuture that succeeds when any of the futures from \a first to
1583 \a last completes. \a first and \a last are iterators to a sequence of futures
1584 packaging type \c T. The returned future packages a value of type
1585 \c {QtFuture::WhenAnyResult<T>} which in turn packages the index of the
1586 first completed \c QFuture and the \c QFuture itself. If \a first equals \a last,
1587 this function returns a ready \c QFuture that has \c -1 for the \c index field in
1588 the QtFuture::WhenAnyResult struct and a default-constructed \c QFuture<T> for
1589 the \c future field. Note that a default-constructed QFuture is a completed
1590 future in a cancelled state.
1591
1592//! [whenAny]
1593 The returned future always completes successfully after the first future
1594 from the specified futures completes. It doesn't matter if the first future
1595 completes with error or is canceled. You can use \c .then() to process the
1596 result after the future returned by \c whenAny() succeeds:
1597//! [whenAny]
1598
1599 \snippet code/src_corelib_thread_qfuture.cpp 26
1600
1601//! [whenAny-note]
1602 \note If the input futures complete on different threads, the future returned
1603 by this method will complete in the thread that the first future completes in.
1604 Therefore, the continuations attached to the future returned by \c whenAny()
1605 cannot always make assumptions about which thread they will be run on. Use the
1606 overload of \c .then() that takes a context object if you want to control which
1607 thread the continuations are invoked on.
1608//! [whenAny-note]
1609
1610 \sa QtFuture::WhenAnyResult
1611*/
1612
1613/*! \fn template<typename... Futures> QFuture<std::variant<std::decay_t<Futures>...>> QtFuture::whenAny(Futures &&... futures)
1614
1615 \since 6.3
1616
1617 Returns a new QFuture that succeeds when any of the \a futures completes.
1618 \a futures can package arbitrary types. The returned future packages the
1619 value of type \c std::variant<Futures...> which in turn packages the first
1620 completed QFuture from \a futures. You can use
1621 \l {https://en.cppreference.com/w/cpp/utility/variant/index} {std::variant::index()}
1622 to find out the index of the future in the sequence of \a futures that
1623 finished first.
1624
1625 \include qfuture.qdoc whenAny
1626
1627 \snippet code/src_corelib_thread_qfuture.cpp 27
1628
1629 \include qfuture.qdoc whenAny-note
1630*/