1/****************************************************************************
2**
3** Copyright (C) 2016 The Qt Company Ltd.
4** Contact: https://www.qt.io/licensing/
5**
6** This file is part of the QtConcurrent module of the Qt Toolkit.
7**
8** $QT_BEGIN_LICENSE:LGPL$
9** Commercial License Usage
10** Licensees holding valid commercial Qt licenses may use this file in
11** accordance with the commercial license agreement provided with the
12** Software or, alternatively, in accordance with the terms contained in
13** a written agreement between you and The Qt Company. For licensing terms
14** and conditions see https://www.qt.io/terms-conditions. For further
15** information use the contact form at https://www.qt.io/contact-us.
16**
17** GNU Lesser General Public License Usage
18** Alternatively, this file may be used under the terms of the GNU Lesser
19** General Public License version 3 as published by the Free Software
20** Foundation and appearing in the file LICENSE.LGPL3 included in the
21** packaging of this file. Please review the following information to
22** ensure the GNU Lesser General Public License version 3 requirements
23** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
24**
25** GNU General Public License Usage
26** Alternatively, this file may be used under the terms of the GNU
27** General Public License version 2.0 or (at your option) the GNU General
28** Public license version 3 or any later version approved by the KDE Free
29** Qt Foundation. The licenses are as published by the Free Software
30** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
31** included in the packaging of this file. Please review the following
32** information to ensure the GNU General Public License requirements will
33** be met: https://www.gnu.org/licenses/gpl-2.0.html and
34** https://www.gnu.org/licenses/gpl-3.0.html.
35**
36** $QT_END_LICENSE$
37**
38****************************************************************************/
39
40#ifndef QTCONCURRENT_THREADENGINE_H
41#define QTCONCURRENT_THREADENGINE_H
42
43#include <QtConcurrent/qtconcurrent_global.h>
44
45#if !defined(QT_NO_CONCURRENT) ||defined(Q_CLANG_QDOC)
46
47#include <QtCore/qthreadpool.h>
48#include <QtCore/qfuture.h>
49#include <QtCore/qdebug.h>
50#include <QtCore/qexception.h>
51#include <QtCore/qwaitcondition.h>
52#include <QtCore/qatomic.h>
53#include <QtCore/qsemaphore.h>
54
55QT_BEGIN_NAMESPACE
56
57
58namespace QtConcurrent {
59
60// The ThreadEngineBarrier counts worker threads, and allows one
61// thread to wait for all others to finish. Tested for its use in
62// QtConcurrent, requires more testing for use as a general class.
63class ThreadEngineBarrier
64{
65private:
66 // The thread count is maintained as an integer in the count atomic
67 // variable. The count can be either positive or negative - a negative
68 // count signals that a thread is waiting on the barrier.
69
70 QAtomicInt count;
71 QSemaphore semaphore;
72public:
73 ThreadEngineBarrier();
74 void acquire();
75 int release();
76 void wait();
77 int currentCount();
78 bool releaseUnlessLast();
79};
80
81enum ThreadFunctionResult { ThrottleThread, ThreadFinished };
82
83// The ThreadEngine controls the threads used in the computation.
84// Can be run in three modes: single threaded, multi-threaded blocking
85// and multi-threaded asynchronous.
86// The code for the single threaded mode is
87class Q_CONCURRENT_EXPORT ThreadEngineBase: public QRunnable
88{
89public:
90 // Public API:
91 ThreadEngineBase();
92 virtual ~ThreadEngineBase();
93 void startSingleThreaded();
94 void startBlocking();
95 void startThread();
96 bool isCanceled();
97 void waitForResume();
98 bool isProgressReportingEnabled();
99 void setProgressValue(int progress);
100 void setProgressRange(int minimum, int maximum);
101 void acquireBarrierSemaphore();
102
103protected: // The user overrides these:
104 virtual void start() {}
105 virtual void finish() {}
106 virtual ThreadFunctionResult threadFunction() { return ThreadFinished; }
107 virtual bool shouldStartThread() { return futureInterface ? !futureInterface->isPaused() : true; }
108 virtual bool shouldThrottleThread() { return futureInterface ? futureInterface->isPaused() : false; }
109private:
110 bool startThreadInternal();
111 void startThreads();
112 void threadExit();
113 bool threadThrottleExit();
114 void run() override;
115 virtual void asynchronousFinish() = 0;
116#ifndef QT_NO_EXCEPTIONS
117 void handleException(const QException &exception);
118#endif
119protected:
120 QFutureInterfaceBase *futureInterface;
121 QThreadPool *threadPool;
122 ThreadEngineBarrier barrier;
123 QtPrivate::ExceptionStore exceptionStore;
124};
125
126
127template <typename T>
128class ThreadEngine : public virtual ThreadEngineBase
129{
130public:
131 typedef T ResultType;
132
133 virtual T *result() { return nullptr; }
134
135 QFutureInterface<T> *futureInterfaceTyped()
136 {
137 return static_cast<QFutureInterface<T> *>(futureInterface);
138 }
139
140 // Runs the user algorithm using a single thread.
141 T *startSingleThreaded()
142 {
143 ThreadEngineBase::startSingleThreaded();
144 return result();
145 }
146
147 // Runs the user algorithm using multiple threads.
148 // This function blocks until the algorithm is finished,
149 // and then returns the result.
150 T *startBlocking()
151 {
152 ThreadEngineBase::startBlocking();
153 return result();
154 }
155
156 // Runs the user algorithm using multiple threads.
157 // Does not block, returns a future.
158 QFuture<T> startAsynchronously()
159 {
160 futureInterface = new QFutureInterface<T>();
161
162 // reportStart() must be called before starting threads, otherwise the
163 // user algorithm might finish while reportStart() is running, which
164 // is very bad.
165 futureInterface->reportStarted();
166 QFuture<T> future = QFuture<T>(futureInterfaceTyped());
167 start();
168
169 acquireBarrierSemaphore();
170 threadPool->start(this);
171 return future;
172 }
173
174 void asynchronousFinish() override
175 {
176 finish();
177 futureInterfaceTyped()->reportFinished(result());
178 delete futureInterfaceTyped();
179 delete this;
180 }
181
182
183 void reportResult(const T *_result, int index = -1)
184 {
185 if (futureInterface)
186 futureInterfaceTyped()->reportResult(_result, index);
187 }
188
189 void reportResults(const QVector<T> &_result, int index = -1, int count = -1)
190 {
191 if (futureInterface)
192 futureInterfaceTyped()->reportResults(_result, index, count);
193 }
194};
195
196// The ThreadEngineStarter class ecapsulates the return type
197// from the thread engine.
198// Depending on how the it is used, it will run
199// the engine in either blocking mode or asynchronous mode.
200template <typename T>
201class ThreadEngineStarterBase
202{
203public:
204 ThreadEngineStarterBase(ThreadEngine<T> *_threadEngine)
205 : threadEngine(_threadEngine) { }
206
207 inline ThreadEngineStarterBase(const ThreadEngineStarterBase &other)
208 : threadEngine(other.threadEngine) { }
209
210 QFuture<T> startAsynchronously()
211 {
212 return threadEngine->startAsynchronously();
213 }
214
215 operator QFuture<T>()
216 {
217 return startAsynchronously();
218 }
219
220protected:
221 ThreadEngine<T> *threadEngine;
222};
223
224
225// We need to factor out the code that dereferences the T pointer,
226// with a specialization where T is void. (code that dereferences a void *
227// won't compile)
228template <typename T>
229class ThreadEngineStarter : public ThreadEngineStarterBase<T>
230{
231 typedef ThreadEngineStarterBase<T> Base;
232 typedef ThreadEngine<T> TypedThreadEngine;
233public:
234 ThreadEngineStarter(TypedThreadEngine *eng)
235 : Base(eng) { }
236
237 T startBlocking()
238 {
239 T t = *this->threadEngine->startBlocking();
240 delete this->threadEngine;
241 return t;
242 }
243};
244
245// Full template specialization where T is void.
246template <>
247class ThreadEngineStarter<void> : public ThreadEngineStarterBase<void>
248{
249public:
250 ThreadEngineStarter<void>(ThreadEngine<void> *_threadEngine)
251 :ThreadEngineStarterBase<void>(_threadEngine) {}
252
253 void startBlocking()
254 {
255 this->threadEngine->startBlocking();
256 delete this->threadEngine;
257 }
258};
259
260//! [qtconcurrentthreadengine-1]
261template <typename ThreadEngine>
262inline ThreadEngineStarter<typename ThreadEngine::ResultType> startThreadEngine(ThreadEngine *threadEngine)
263{
264 return ThreadEngineStarter<typename ThreadEngine::ResultType>(threadEngine);
265}
266
267} // namespace QtConcurrent
268
269
270QT_END_NAMESPACE
271
272#endif // QT_NO_CONCURRENT
273
274#endif
275