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(QThreadPool *pool);
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 void reportIfSuspensionDone() const;
103
104protected: // The user overrides these:
105 virtual void start() {}
106 virtual void finish() {}
107 virtual ThreadFunctionResult threadFunction() { return ThreadFinished; }
108 virtual bool shouldStartThread() { return !shouldThrottleThread(); }
109 virtual bool shouldThrottleThread()
110 {
111 return futureInterface ? (futureInterface->isSuspending() || futureInterface->isSuspended())
112 : false;
113 }
114
115private:
116 bool startThreadInternal();
117 void startThreads();
118 void threadExit();
119 bool threadThrottleExit();
120 void run() override;
121 virtual void asynchronousFinish() = 0;
122#ifndef QT_NO_EXCEPTIONS
123 void handleException(const QException &exception);
124#endif
125protected:
126 QFutureInterfaceBase *futureInterface;
127 QThreadPool *threadPool;
128 ThreadEngineBarrier barrier;
129 QtPrivate::ExceptionStore exceptionStore;
130 QBasicMutex mutex;
131};
132
133
134template <typename T>
135class ThreadEngine : public ThreadEngineBase
136{
137public:
138 typedef T ResultType;
139
140 ThreadEngine(QThreadPool *pool) : ThreadEngineBase(pool) {}
141
142 virtual T *result() { return nullptr; }
143
144 QFutureInterface<T> *futureInterfaceTyped()
145 {
146 return static_cast<QFutureInterface<T> *>(futureInterface);
147 }
148
149 // Runs the user algorithm using a single thread.
150 T *startSingleThreaded()
151 {
152 ThreadEngineBase::startSingleThreaded();
153 return result();
154 }
155
156 // Runs the user algorithm using multiple threads.
157 // This function blocks until the algorithm is finished,
158 // and then returns the result.
159 T *startBlocking()
160 {
161 ThreadEngineBase::startBlocking();
162 return result();
163 }
164
165 // Runs the user algorithm using multiple threads.
166 // Does not block, returns a future.
167 QFuture<T> startAsynchronously()
168 {
169 futureInterface = new QFutureInterface<T>();
170
171 // reportStart() must be called before starting threads, otherwise the
172 // user algorithm might finish while reportStart() is running, which
173 // is very bad.
174 futureInterface->reportStarted();
175 QFuture<T> future = QFuture<T>(futureInterfaceTyped());
176 start();
177
178 acquireBarrierSemaphore();
179 threadPool->start(this);
180 return future;
181 }
182
183 void asynchronousFinish() override
184 {
185 finish();
186 futureInterfaceTyped()->reportFinished(result());
187 delete futureInterfaceTyped();
188 delete this;
189 }
190
191
192 void reportResult(const T *_result, int index = -1)
193 {
194 if (futureInterface)
195 futureInterfaceTyped()->reportResult(_result, index);
196 }
197
198 void reportResults(const QList<T> &_result, int index = -1, int count = -1)
199 {
200 if (futureInterface)
201 futureInterfaceTyped()->reportResults(_result, index, count);
202 }
203};
204
205// The ThreadEngineStarter class ecapsulates the return type
206// from the thread engine.
207// Depending on how the it is used, it will run
208// the engine in either blocking mode or asynchronous mode.
209template <typename T>
210class ThreadEngineStarterBase
211{
212public:
213 ThreadEngineStarterBase(ThreadEngine<T> *_threadEngine)
214 : threadEngine(_threadEngine) { }
215
216 inline ThreadEngineStarterBase(const ThreadEngineStarterBase &other)
217 : threadEngine(other.threadEngine) { }
218
219 QFuture<T> startAsynchronously()
220 {
221 return threadEngine->startAsynchronously();
222 }
223
224 operator QFuture<T>()
225 {
226 return startAsynchronously();
227 }
228
229protected:
230 ThreadEngine<T> *threadEngine;
231};
232
233
234// We need to factor out the code that dereferences the T pointer,
235// with a specialization where T is void. (code that dereferences a void *
236// won't compile)
237template <typename T>
238class ThreadEngineStarter : public ThreadEngineStarterBase<T>
239{
240 typedef ThreadEngineStarterBase<T> Base;
241 typedef ThreadEngine<T> TypedThreadEngine;
242public:
243 ThreadEngineStarter(TypedThreadEngine *eng)
244 : Base(eng) { }
245
246 T startBlocking()
247 {
248 T t = *this->threadEngine->startBlocking();
249 delete this->threadEngine;
250 return t;
251 }
252};
253
254// Full template specialization where T is void.
255template <>
256class ThreadEngineStarter<void> : public ThreadEngineStarterBase<void>
257{
258public:
259 ThreadEngineStarter(ThreadEngine<void> *_threadEngine)
260 : ThreadEngineStarterBase<void>(_threadEngine) {}
261
262 void startBlocking()
263 {
264 this->threadEngine->startBlocking();
265 delete this->threadEngine;
266 }
267};
268
269//! [qtconcurrentthreadengine-1]
270template <typename ThreadEngine>
271inline ThreadEngineStarter<typename ThreadEngine::ResultType> startThreadEngine(ThreadEngine *threadEngine)
272{
273 return ThreadEngineStarter<typename ThreadEngine::ResultType>(threadEngine);
274}
275
276} // namespace QtConcurrent
277
278
279QT_END_NAMESPACE
280
281#endif // QT_NO_CONCURRENT
282
283#endif
284