summaryrefslogtreecommitdiffstats
path: root/src/corelib/doc/snippets/code/src_corelib_thread_qfuture.cpp
blob: ffb78dc4c8aad4ae9bc96d0f3e005671c2337845 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
/****************************************************************************
**
** Copyright (C) 2016 The Qt Company Ltd.
** Contact: https://www.qt.io/licensing/
**
** This file is part of the documentation of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:BSD$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and The Qt Company. For licensing terms
** and conditions see https://www.qt.io/terms-conditions. For further
** information use the contact form at https://www.qt.io/contact-us.
**
** BSD License Usage
** Alternatively, you may use this file under the terms of the BSD license
** as follows:
**
** "Redistribution and use in source and binary forms, with or without
** modification, are permitted provided that the following conditions are
** met:
**   * Redistributions of source code must retain the above copyright
**     notice, this list of conditions and the following disclaimer.
**   * Redistributions in binary form must reproduce the above copyright
**     notice, this list of conditions and the following disclaimer in
**     the documentation and/or other materials provided with the
**     distribution.
**   * Neither the name of The Qt Company Ltd nor the names of its
**     contributors may be used to endorse or promote products derived
**     from this software without specific prior written permission.
**
**
** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."
**
** $QT_END_LICENSE$
**
****************************************************************************/

//! [0]
QFuture<QString> future = ...;

QFuture<QString>::const_iterator i;
for (i = future.constBegin(); i != future.constEnd(); ++i)
    cout << *i << Qt::endl;
//! [0]


//! [1]
QFuture<QString> future;
...
QFutureIterator<QString> i(future);
while (i.hasNext())
    QString s = i.next();
//! [1]


//! [2]
QFutureIterator<QString> i(future);
i.toBack();
while (i.hasPrevious())
    QString s = i.previous();
//! [2]

//! [3]
using NetworkReply = std::variant<QByteArray, QNetworkReply::NetworkError>;

enum class IOError { FailedToRead, FailedToWrite };
using IOResult = std::variant<QString, IOError>;
//! [3]

//! [4]
QFuture<IOResult> future = QtConcurrent::run([url] {
        ...
        return NetworkReply(QNetworkReply::TimeoutError);
}).then([](NetworkReply reply) {
    if (auto error = std::get_if<QNetworkReply::NetworkError>(&reply))
        return IOResult(IOError::FailedToRead);

    auto data = std::get_if<QByteArray>(&reply);
    // try to write *data and return IOError::FailedToWrite on failure
    ...
});

auto result = future.result();
if (auto filePath = std::get_if<QString>(&result)) {
    // do something with *filePath
else
    // process the error
//! [4]

//! [5]
QFuture<int> future = ...;
    future.then([](QFuture<int> f) {
        try {
            ...
            auto result = f.result();
            ...
        } catch (QException &e) {
            // handle the exception
        }
    }).then(...);
//! [5]

//! [6]
QFuture<int> future = ...;
auto continuation = future.then([](int res1){ ... }).then([](int res2){ ... })...
...
// future throws an exception
try {
    auto result = continuation.result();
} catch (QException &e) {
    // handle the exception
}
//! [6]

//! [7]
QFuture<int> future = ...;
auto resultFuture = future.then([](int res) {
    ...
    throw Error();
    ...
}).onFailed([](const Error &e) {
    // Handle exceptions of type Error
    ...
    return -1;
}).onFailed([] {
    // Handle all other types of errors
    ...
    return -1;
});

auto result = resultFuture.result(); // result is -1
//! [7]

//! [8]
QFuture<int> future = ...;
future.then([](int res) {
    ...
    throw std::runtime_error("message");
    ...
}).onFailed([](const std::exception &e) {
    // This handler will be invoked
}).onFailed([](const std::runtime_error &e) {
    // This handler won't be invoked, because of the handler above.
});
//! [8]

//! [9]
QFuture<int> future = ...;
auto resultFuture = future.then([](int res) {
    ...
    throw Error("message");
    ...
}).onFailed([](const std::exception &e) {
    // Won't be invoked
}).onFailed([](const QException &e) {
    // Won't be invoked
});

try {
    auto result = resultFuture.result();
} catch(...) {
    // Handle the exception
}
//! [9]

//! [10]
class Object : public QObject
{
    Q_OBJECT
    ...
signals:
    void noArgSignal();
    void singleArgSignal(int value);
    void multipleArgs(int value1, double value2, const QString &value3);
};
//! [10]

//! [11]
Object object;
QFuture<void> voidFuture = QtFuture::connect(&object, &Object::noArgSignal);
QFuture<int> intFuture = QtFuture::connect(&object, &Object::singleArgSignal);

using Args = std::tuple<int, double, QString>;
QFuture<Args> tupleFuture = QtFuture::connect(&object, &Object::multipleArgs)
//! [11]

//! [12]
QtFuture::connect(&object, &Object::singleArgSignal).then([](int value) {
    // do something with the value
});
//! [12]

//! [13]
QtFuture::connect(&object, &Object::singleArgSignal).then(QtFuture::Launch::Async, [](int value) {
    // this will run in a new thread
});
//! [13]

//! [14]
QtFuture::connect(&object, &Object::singleArgSignal).then([](int value) {
    ...
    throw std::exception();
    ...
}).onFailed([](const std::exception &e) {
    // handle the exception
}).onFailed([] {
    // handle other exceptions
});
//! [14]

//! [15]
QFuture<int> testFuture = ...;
auto resultFuture = testFuture.then([](int res) {
    // Block 1
}).onCanceled([] {
    // Block 2
}).onFailed([] {
    // Block 3
}).then([] {
    // Block 4
}).onFailed([] {
    // Block 5
}).onCanceled([] {
    // Block 6
});
//! [15]

//! [16]
QFuture<int> testFuture = ...;
auto resultFuture = testFuture.then([](int res) {
    // Block 1
}).onFailed([] {
    // Block 3
}).then([] {
    // Block 4
}).onFailed([] {
    // Block 5
}).onCanceled([] {
    // Block 6
});
//! [16]

//! [17]
// somewhere in the main thread
auto future = QtConcurrent::run([] {
    // This will run in a separate thread
    ...
}).then(this, [] {
   // Update UI elements
});
//! [17]

//! [18]
auto future = QtConcurrent::run([] {
    ...
}).then(this, [] {
   // Update UI elements
}).then([] {
    // This will also run in the main thread
});
//! [18]

//! [19]
// somewhere in the main thread
auto future = QtConcurrent::run([] {
    // This will run in a separate thread
    ...
    throw std::exception();
}).onFailed(this, [] {
   // Update UI elements
});
//! [19]

//! [20]
QObject *context = ...;
auto future = cachedResultsReady ? QtFuture::makeReadyFuture(results)
                                 : QtConcurrent::run([] { /* compute results */});
auto continuation = future.then(context, [] (Results results) {
    // Runs in the context's thread
}).then([] {
    // May or may not run in the context's thread
});
//! [20]

//! [21]
QFuture<int> testFuture = ...;
auto resultFuture = testFuture.then([](int res) {
    // Block 1
    ...
    return 1;
}).then([](int res) {
    // Block 2
    ...
    return 2;
}).onCanceled([] {
    // Block 3
    ...
    return -1;
});
//! [21]

//! [22]
QList<QFuture<int>> inputFutures {...};

// whenAll has type QFuture<QList<QFuture<int>>>
auto whenAll = QtFuture::whenAll(inputFutures.begin(), inputFutures.end());

// whenAllVector has type QFuture<std::vector<QFuture<int>>>
auto whenAllVector =
        QtFuture::whenAll<std::vector<QFuture<int>>>(inputFutures.begin(), inputFutures.end());
//! [22]

//! [23]
QList<QFuture<int>> inputFutures {...};

QtFuture::whenAll(inputFutures.begin(), inputFutures.end())
        .then([](const QList<QFuture<int>> &results) {
            for (auto future : results) {
                if (future.isCanceled())
                    // handle the cancellation (possibly due to an exception)
                else
                    // do something with the result
            }
        });
//! [23]

//! [24]

QFuture<int> intFuture = ...;
QFuture<QString> stringFuture = ...;
QFuture<void> voidFuture = ...;

using FuturesVariant = std::variant<QFuture<int>, QFuture<QString>, QFuture<void>>;

// whenAll has type QFuture<QList<FuturesVariant>>
auto whenAll = QtFuture::whenAll(intFuture, stringFuture, voidFuture);

// whenAllVector has type QFuture<std::vector<FuturesVariant>>
auto whenAllVector =
        QtFuture::whenAll<std::vector<FuturesVariant>>(intFuture, stringFuture, voidFuture);

//! [24]

//! [25]
QFuture<int> intFuture = ...;
QFuture<QString> stringFuture = ...;
QFuture<void> voidFuture = ...;

using FuturesVariant = std::variant<QFuture<int>, QFuture<QString>, QFuture<void>>;

QtFuture::whenAll(intFuture, stringFuture, voidFuture)
        .then([](const QList<FuturesVariant> &results) {
            ...
            for (auto result : results)
            {
                // assuming handleResult() is overloaded based on the QFuture type
                std::visit([](auto &&future) { handleResult(future); }, result);
            }
            ...
        });
//! [25]

//! [26]
QList<QFuture<int>> inputFutures = ...;

QtFuture::whenAny(inputFutures.begin(), inputFutures.end())
        .then([](const QtFuture::WhenAnyResult<int> &result) {
            qsizetype index = result.index;
            QFuture<int> future = result.future;
            // ...
        });
//! [26]

//! [27]
QFuture<int> intFuture = ...;
QFuture<QString> stringFuture = ...;
QFuture<void> voidFuture = ...;

using FuturesVariant = std::variant<QFuture<int>, QFuture<QString>, QFuture<void>>;

QtFuture::whenAny(intFuture, stringFuture, voidFuture).then([](const FuturesVariant &result) {
    ...
    // assuming handleResult() is overloaded based on the QFuture type
    std::visit([](auto &&future) { handleResult(future); }, result);
    ...
});
//! [27]