swift
Loading...
Searching...
No Matches
worker.h
Go to the documentation of this file.
1// SPDX-FileCopyrightText: Copyright (C) 2014 swift Project Community / Contributors
2// SPDX-License-Identifier: GPL-3.0-or-later OR LicenseRef-swift-pilot-client-1
3
5
6#ifndef SWIFT_MISC_WORKER_H
7#define SWIFT_MISC_WORKER_H
8
9#include <algorithm>
10#include <atomic>
11#include <functional>
12#include <future>
13#include <memory>
14#include <type_traits>
15
16#include <QMetaObject>
17#include <QMetaType>
18#include <QMutex>
19#include <QMutexLocker>
20#include <QObject>
21#include <QPointer>
22#include <QString>
23#include <QThread>
24#include <QTimer>
25#include <QVariant>
26#include <QtGlobal>
27
28#include "misc/invoke.h"
29#include "misc/promise.h"
31
32namespace swift::misc
33{
38 {
40
41 public:
43 explicit CRegularThread(QObject *parent = nullptr) : QThread(parent) {}
44
46 ~CRegularThread() override;
47
49 CRegularThread(const CRegularThread &) = delete;
50
53
56
59
60 protected:
62 void run() override;
63
64 private:
65 std::atomic<void *> m_handle { nullptr };
66 };
67
72 {
74
75 public:
77 ~CWorkerBase() override;
78
80 CWorkerBase(const CWorkerBase &) = delete;
81
83 CWorkerBase &operator=(const CWorkerBase &) = delete;
84
87
90
92 static const QStringList &getLogCategories();
93
96 template <typename T, typename F>
97 void then(T *context, F functor)
98 {
99 Q_ASSERT(context->thread() == QThread::currentThread());
100 QMutexLocker lock(&m_finishedMutex);
101 connect(this, &CWorkerBase::finished, context, functor);
102 if (m_finished)
103 {
104 private_ns::invokeSlot(functor, context);
105 }
106 }
107
110 template <typename F>
111 void then(F functor)
112 {
113 QMutexLocker lock(&m_finishedMutex);
114 connect(this, &CWorkerBase::finished, functor);
115 if (m_finished)
116 {
117 functor();
118 }
119 }
120
123 bool isFinished() const
124 {
125 QMutexLocker lock(&m_finishedMutex);
126 return m_finished;
127 }
128
131 template <typename F>
132 void doIfFinished(F functor) const
133 {
134 QMutexLocker lock(&m_finishedMutex);
135 if (m_finished)
136 {
137 functor();
138 }
139 }
140
143 template <typename F>
144 void doIfNotFinished(F functor) const
145 {
146 QMutexLocker lock(&m_finishedMutex);
147 if (!m_finished)
148 {
149 functor();
150 }
151 }
152
155 template <typename F1, typename F2>
156 void doIfFinishedElse(F1 ifFunctor, F2 elseFunctor) const
157 {
158 QMutexLocker lock(&m_finishedMutex);
159 if (m_finished)
160 {
161 ifFunctor();
162 }
163 else
164 {
165 elseFunctor();
166 }
167 }
168
171 void waitForFinished() noexcept;
172
175 void abandon() noexcept;
176
178 void abandonAndWait() noexcept;
179
181 static const QSet<CWorkerBase *> &allWorkers() { return s_allWorkers; }
182
183 signals:
186
189 void finished();
190
191 protected:
193 CWorkerBase();
194
197 bool isAbandoned() const;
198
200 bool hasStarted() const { return m_started; }
201
203 void setStarted() { m_started = true; }
204
207 {
208 QMutexLocker lock(&m_finishedMutex);
209 m_finished = true;
210 emit finished();
211 }
212
213 private:
214 virtual void quit() noexcept {}
215 virtual void quitAndWait() noexcept { waitForFinished(); }
216
217 bool m_started = false;
218 bool m_finished = false;
219 mutable QRecursiveMutex m_finishedMutex;
220 static QSet<CWorkerBase *> s_allWorkers;
221 };
222
229 class SWIFT_MISC_EXPORT CWorker final : public CWorkerBase
230 {
232
233 public:
242 template <typename F>
243 static CWorker *fromTask(QObject *owner, const QString &name, F &&task)
244 {
245 // NOLINTNEXTLINE(cppcoreguidelines-init-variables)
246 int typeId = qMetaTypeId<std::decay_t<decltype(std::forward<F>(task)())>>();
247 return fromTaskImpl(owner, name, typeId, [task = std::forward<F>(task)]() mutable {
248 if constexpr (std::is_void_v<decltype(task())>)
249 {
250 std::move(task)();
251 return QVariant();
252 }
253 else
254 {
255 return QVariant::fromValue(std::move(task)());
256 }
257 });
258 }
259
263 template <typename R, typename F>
264 void thenWithResult(F functor)
265 {
266 Q_ASSERT_X(m_result.canConvert<R>(), Q_FUNC_INFO, "Type in thenWithResult must match return type of task");
267 then([this, functor]() { functor(this->resultNoWait<R>()); });
268 }
269
273 template <typename R, typename T, typename F>
274 void thenWithResult(T *context, F functor)
275 {
276 Q_ASSERT_X(m_result.canConvert<R>(), Q_FUNC_INFO, "Type in thenWithResult must match return type of task");
277
278 // MS 2018-10 It is possible that a queued finished() signal will be delivered after the worker was
279 // destroyed, so we can't refer to the this pointer inside the contextual then() lambda.
280 // Therefore we use a promise to extract the result from a non-contextual then(). See T414.
281 auto promise = std::make_shared<std::promise<R>>();
282 auto future = promise->get_future().share();
283 then([this, promise]() { promise->set_value(this->resultNoWait<R>()); });
284 then(context, [context, functor, future]() { private_ns::invokeSlot(functor, context, future.get()); });
285 }
286
290 template <typename R>
292 {
294 return this->resultNoWait<R>();
295 }
296
297 private slots:
299 void ps_runTask();
300
301 private:
302 CWorker(const std::function<QVariant()> &task) : m_task(task) {}
303 static CWorker *fromTaskImpl(QObject *owner, const QString &name, int typeId,
304 const std::function<QVariant()> &task);
305
306 template <typename R>
307 R resultNoWait()
308 {
309 Q_ASSERT(m_result.canConvert<R>());
310 return m_result.value<R>();
311 }
312
313 std::function<QVariant()> m_task;
314 QVariant m_result;
315 };
316
321 {
323
324 public:
330 CContinuousWorker(QObject *owner, const QString &name);
331
334
338 void quit() noexcept final;
339
342 void quitAndWait() noexcept final;
343
346 bool isEnabled() const { return m_enabled; }
347
349 const QString &getName() { return m_name; }
350
352 const QObject *owner() const { return m_owner; }
353
354 protected:
356 virtual void initialize() {}
357
359 virtual void cleanup() {}
360
363 virtual void beforeQuit() noexcept {}
364
366 virtual unsigned long waitTimeoutMs() const { return 15 * 1000; }
367
368 private:
370 void finish();
371
374 void setEnabled(bool enabled) { m_enabled = enabled; }
375
376 using CWorkerBase::setStarted;
377 using CWorkerBase::setFinished;
378
379 QObject *m_owner = nullptr;
380 QString m_name;
381 std::atomic<bool> m_enabled { true };
382 };
383} // namespace swift::misc
384
385#endif // SWIFT_MISC_WORKER_H
virtual void beforeQuit() noexcept
Called before quit is called.
Definition worker.h:363
bool isEnabled() const
Enabled (running)?
Definition worker.h:346
const QObject * owner() const
Owner of the worker.
Definition worker.h:352
virtual void cleanup()
Called when the thread is finished.
Definition worker.h:359
void quit() noexcept final
Stops the thread the next time around its event loop. The thread and the worker will then be deleted.
Definition worker.cpp:203
virtual void initialize()
Called when the thread is started.
Definition worker.h:356
virtual unsigned long waitTimeoutMs() const
Wait time for quitAndWait, 0 means not waiting.
Definition worker.h:366
void quitAndWait() noexcept final
Calls quit() and blocks until the thread is finished.
Definition worker.cpp:218
void start(QThread::Priority priority=QThread::InheritPriority)
Starts a thread and moves the worker into it.
Definition worker.cpp:174
CContinuousWorker(QObject *owner, const QString &name)
Constructor.
Definition worker.cpp:168
const QString & getName()
Name of the worker.
Definition worker.h:349
Just a subclass of QThread whose destructor waits for the thread to finish.
Definition worker.h:38
CRegularThread(QObject *parent=nullptr)
Constructor.
Definition worker.h:43
CRegularThread & operator=(CRegularThread &&)=delete
Move assignment.
CRegularThread & operator=(const CRegularThread &)=delete
Copy assignment.
CRegularThread(CRegularThread &&)=delete
Move constructor.
CRegularThread(const CRegularThread &)=delete
Copy constructor.
CWorkerBase & operator=(const CWorkerBase &)=delete
Copy assignment.
void doIfFinished(F functor) const
Executes some code (in the caller's thread) if the task has finished.
Definition worker.h:132
void aboutToStart()
Emitted when the task is about to start.
void then(T *context, F functor)
Connects to a functor or method which will be called when the task is finished.
Definition worker.h:97
void setStarted()
Mark the task as started.
Definition worker.h:203
CWorkerBase(const CWorkerBase &)=delete
Copy constructor.
CWorkerBase(CWorkerBase &&)=delete
Move constructor.
static const QStringList & getLogCategories()
Log categories.
Definition worker.cpp:131
void finished()
Emitted when the task is finished.
void then(F functor)
Connects to a functor which will be called when the task is finished.
Definition worker.h:111
static const QSet< CWorkerBase * > & allWorkers()
All workers currently existing.
Definition worker.h:181
bool isAbandoned() const
For the task to check whether it can finish early.
Definition worker.cpp:162
bool isFinished() const
Returns true if the task has finished.
Definition worker.h:123
CWorkerBase & operator=(CWorkerBase &&)=delete
Move assignment.
void doIfNotFinished(F functor) const
Executes some code (in the caller's thread) if the task has not finished.
Definition worker.h:144
bool hasStarted() const
True if the worker has started.
Definition worker.h:200
void doIfFinishedElse(F1 ifFunctor, F2 elseFunctor) const
Executes some code (in the caller's thread) if the task has finished and some different code if it ha...
Definition worker.h:156
void setFinished()
Mark the task as finished.
Definition worker.h:206
void waitForFinished() noexcept
Blocks until the task is finished.
Definition worker.cpp:137
Class for doing some arbitrary parcel of work in its own thread.
Definition worker.h:230
R result()
Returns the result of the task, waiting for it to finish if necessary.
Definition worker.h:291
static CWorker * fromTask(QObject *owner, const QString &name, F &&task)
Returns a new worker object which lives in a new thread.
Definition worker.h:243
void thenWithResult(T *context, F functor)
Connects to a functor or method to which will be passed the result when the task is finished.
Definition worker.h:274
void thenWithResult(F functor)
Connects to a functor to which will be passed the result when the task is finished.
Definition worker.h:264
Free functions in swift::misc.
QObject(QObject *parent)
Q_OBJECTQ_OBJECT
QMetaObject::Connection connect(const QObject *sender, PointerToMemberFunction signal, Functor functor)
QObject * parent() const const
QThread(QObject *parent)
QThread * currentThread()
QVariant fromValue(T &&value)
#define SWIFT_MISC_EXPORT
Export a class or function from the library.