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