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