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