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
src_concurrent_qtconcurrenttask.cpp
Go to the documentation of this file.
1// Copyright (C) 2020 The Qt Company Ltd.
2// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR BSD-3-Clause
3
4//! [0]
5QtConcurrent::task([]{ qDebug("Hello, world!"); }).spawn();
6//! [0]
7
8//! [1]
9auto task = [](const QString &s){ qDebug() << ("Hello, " + s); };
10QtConcurrent::task(std::move(task))
11 .withArguments("world!")
12 .spawn();
13//! [1]
14
15//! [2]
16QString s("Hello, ");
17QtConcurrent::task([](QString &s){ s.append("world!"); })
18 .withArguments(std::ref(s))
19 .spawn();
20//! [2]
21
22//! [3]
23auto future = QtConcurrent::task([]{ return 42; }).spawn();
24auto result = future.result(); // result == 42
25//! [3]
26
27//! [4]
28std::is_invocable_v<std::decay_t<Task>, std::decay_t<Args>...>
29//! [4]
30
31//! [5]
32QVariant value(42);
33auto result = QtConcurrent::task([](const QVariant &var){return qvariant_cast<int>(var);})
34 .withArguments(value)
35 .spawn()
36 .result(); // result == 42
37//! [5]
38
39//! [6]
40QString result("Hello, world!");
41
42QtConcurrent::task(&QString::chop)
43 .withArguments(&result, 8)
44 .spawn()
45 .waitForFinished(); // result == "Hello"
46//! [6]
47
48//! [7]
49auto result = QtConcurrent::task(std::plus<int>())
50 .withArguments(40, 2)
51 .spawn()
52 .result() // result == 42
53//! [7]
54
55//! [8]
56struct CallableWithState
57{
58 void operator()(int newState) { state = newState; }
59
60 // ...
61};
62
63// ...
64
66
67QtConcurrent::task(std::ref(object))
68 .withArguments(42)
69 .spawn()
70 .waitForFinished(); // The object's state is set to 42
71//! [8]
72
73//! [9]
75QtConcurrent::task([]{ return 42; }).onThreadPool(pool).spawn();
76//! [9]
77
78//! [10]
79QtConcurrent::task([]{ return 42; }).withPriority(10).spawn();
80//! [10]
81
82//! [11]
83QtConcurrent::task([]{ qDebug("Hello, world!"); }).spawn(FutureResult::Ignore);
84//! [11]
85
86//! [12]
87void increment(QPromise<int> &promise, int i)
88{
89 promise.addResult(i + 1);
90}
91
92int result = QtConcurrent::task(&increment).withArguments(10).spawn().result(); // result == 11
93//! [12]
QFuture< void > future
[5]
QThreadPool pool
[8]
QtConcurrent::task([]{ qDebug("Hello, world!");}).spawn(FutureResult void increment(QPromise< int > &promise, int i)
[10]
CallableWithState object
auto s
[6]