1// Copyright (C) 2016 The Qt Company Ltd.
2// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
3
4#ifndef QFUTURESYNCHRONIZER_H
5#define QFUTURESYNCHRONIZER_H
6
7#include <QtCore/qfuture.h>
8
9QT_REQUIRE_CONFIG(future);
10
11QT_BEGIN_NAMESPACE
12
13
14template <typename T>
15class QFutureSynchronizer
16{
17 Q_DISABLE_COPY(QFutureSynchronizer)
18
19public:
20 Q_NODISCARD_CTOR QFutureSynchronizer() : m_cancelOnWait(false) { }
21 Q_NODISCARD_CTOR
22 explicit QFutureSynchronizer(QFuture<T> future)
23 : m_cancelOnWait(false)
24 { addFuture(future: std::move(future)); }
25 ~QFutureSynchronizer() { waitForFinished(); }
26
27 void setFuture(QFuture<T> future)
28 {
29 waitForFinished();
30 m_futures.clear();
31 addFuture(future: std::move(future));
32 }
33
34 void addFuture(QFuture<T> future)
35 {
36 m_futures.append(std::move(future));
37 }
38
39 void waitForFinished()
40 {
41 if (m_cancelOnWait) {
42 for (int i = 0; i < m_futures.size(); ++i) {
43 m_futures[i].cancel();
44 }
45 }
46
47 for (int i = 0; i < m_futures.size(); ++i) {
48 m_futures[i].waitForFinished();
49 }
50 }
51
52 void clearFutures()
53 {
54 m_futures.clear();
55 }
56
57 QList<QFuture<T> > futures() const
58 {
59 return m_futures;
60 }
61
62 void setCancelOnWait(bool enabled)
63 {
64 m_cancelOnWait = enabled;
65 }
66
67 bool cancelOnWait() const
68 {
69 return m_cancelOnWait;
70 }
71
72protected:
73 QList<QFuture<T>> m_futures;
74 bool m_cancelOnWait;
75};
76
77QT_END_NAMESPACE
78
79#endif // QFUTURESYNCHRONIZER_H
80

source code of qtbase/src/corelib/thread/qfuturesynchronizer.h