swift
Loading...
Searching...
No Matches
worker.cpp
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
4#include "misc/worker.h"
5
6#include <future>
7
8#include <QPointer>
9#include <QTimer>
10
11#include "misc/logmessage.h"
12#include "misc/threadutils.h"
13#include "misc/verify.h"
14
15#ifdef Q_OS_WIN32
16# include <Windows.h>
17#endif
18
19namespace swift::misc
20{
21 QSet<CWorkerBase *> CWorkerBase::s_allWorkers;
22
24 {
25#ifdef Q_OS_WIN32
26 m_handle = GetCurrentThread();
28 m_handle = nullptr;
29#else
31#endif
32 }
33
35 {
36 const QString name = this->objectName();
37
38#ifdef Q_OS_WIN32
39 auto handle = m_handle.load();
40 if (handle)
41 {
42 const auto status = WaitForSingleObject(handle, 0);
43 if (isRunning())
44 {
45 switch (status)
46 {
47 default:
48 case WAIT_FAILED: qWarning() << "Thread" << name << "unspecified error"; break;
49 case WAIT_OBJECT_0: qWarning() << "Thread" << name << "unsafely terminated by program shutdown"; break;
50 case WAIT_TIMEOUT: break;
51 }
52 }
53 }
54#endif
55 quit();
56
57 // the wait avoids: QThread: Destroyed while thread is still running
58 const unsigned long timeoutMs = 5 * 1000;
59 const bool ok = wait(timeoutMs);
61 const QString as = QStringLiteral("Wait timeout after %1ms for '%2'").arg(timeoutMs).arg(name);
62 const QByteArray asBA = as.toLatin1();
63 SWIFT_AUDIT_X(ok, Q_FUNC_INFO,
64 asBA); // MS 2018-09 assert because we want a stack trace of all threads, via breakpad
65 Q_UNUSED(ok)
66 }
67
68 CWorker *CWorker::fromTaskImpl(QObject *owner, const QString &name, int typeId,
69 const std::function<QVariant()> &task)
70 {
71 auto *worker = new CWorker(task);
72 emit worker->aboutToStart();
73 worker->setStarted();
74 auto *thread = new CRegularThread(owner);
75
76 if (typeId != QMetaType::Void)
77 {
78 worker->m_result = QVariant(QMetaType(typeId), nullptr);
79 }
80
81 const QString ownerName =
82 owner->objectName().isEmpty() ? owner->metaObject()->className() : owner->objectName();
83 thread->setObjectName(ownerName + ":" + name);
84 worker->setObjectName(name);
85
86 worker->moveToThread(thread);
87 const bool s = QMetaObject::invokeMethod(worker, &CWorker::ps_runTask);
88 Q_ASSERT_X(s, Q_FUNC_INFO, "cannot invoke");
89 Q_UNUSED(s)
90 thread->start();
91 return worker;
92 }
93
94 void CWorker::ps_runTask()
95 {
96 m_result = m_task();
97
98 this->setFinished();
99
100 QThread *workerThread = this->thread();
101 Q_ASSERT_X(workerThread->thread()->isRunning(), Q_FUNC_INFO, "Owner thread's event loop already ended");
102
103 // MS 2018-09 Now we post the DeferredDelete event from within the worker thread, but rely on it being
104 // dispatched
105 // by the owner thread. Posted events are moved along with the object when moveToThread is called.
106 this->deleteLater();
107
108 this->moveToThread(
109 workerThread
110 ->thread()); // move worker back to the thread which constructed it, so there is no race on deletion
111 // must not access the worker beyond this point, as it now lives in the owner's thread and could be deleted at
112 // any moment
113
114 QMetaObject::invokeMethod(workerThread, [workerThread] {
115 // quit and wait is redundant as the CRegularThread dtor will do that anyway, but put here for debugging
116 workerThread->quit();
117 const bool ok = workerThread->wait(5000);
118 const QString as = QStringLiteral("Worker thread '%2' refuses to stop after worker finished")
119 .arg(workerThread->objectName());
120 const QByteArray asBA = as.toLatin1();
121 SWIFT_AUDIT_X(ok, Q_FUNC_INFO, asBA);
122
123 workerThread->deleteLater();
124 });
125 }
126
127 CWorkerBase::CWorkerBase() { s_allWorkers.insert(this); }
128
129 CWorkerBase::~CWorkerBase() { s_allWorkers.remove(this); }
130
132 {
133 static const QStringList cats { CLogCategories::worker() };
134 return cats;
135 }
136
138 {
139 std::promise<void> promise;
140 then([&] { promise.set_value(); });
141 promise.get_future().wait();
142 }
143
144 void CWorkerBase::abandon() noexcept
145 {
146 if (thread() != thread()->thread())
147 {
149 }
150 quit();
151 }
152
154 {
155 if (thread() != thread()->thread())
156 {
158 }
159 quitAndWait();
160 }
161
163 {
164 Q_ASSERT(thread() == QThread::currentThread());
166 }
167
168 CContinuousWorker::CContinuousWorker(QObject *owner, const QString &name) : m_owner(owner), m_name(name)
169 {
170 Q_ASSERT_X(!name.isEmpty(), Q_FUNC_INFO, "Empty name");
171 this->setObjectName(m_name);
172 }
173
175 {
176 SWIFT_VERIFY_X(!hasStarted(), Q_FUNC_INFO, "Tried to start a worker that was already started");
177 if (hasStarted())
178 {
179 return;
180 }
181
182 // avoid message "QObject: Cannot create children for a parent that is in a different thread"
183 Q_ASSERT_X(CThreadUtils::isInThisThread(m_owner), Q_FUNC_INFO, "Needs to be started in owner thread");
184 emit this->aboutToStart();
185 setStarted();
186 auto *thread = new CRegularThread(m_owner);
187
188 Q_ASSERT(m_owner); // must not be null
189 if (m_owner)
190 {
191 const QString ownerName =
192 m_owner->objectName().isEmpty() ? m_owner->metaObject()->className() : m_owner->objectName();
193 thread->setObjectName(ownerName + ": " + m_name);
194 }
195
199 connect(thread, &QThread::finished, this, &CContinuousWorker::finish);
200 thread->start(priority);
201 }
202
204 {
205 this->setEnabled(false);
206
207 // already in owner's thread? then return
208 if (this->thread() == m_owner->thread())
209 {
210 return;
211 }
212
213 // remark: cannot stop timer here, as I am normally not in the correct thread
214 this->beforeQuit();
215 thread()->quit();
216 }
217
219 {
220 this->setEnabled(false);
221
222 // already in owner's thread? then return
223 if (this->thread() == m_owner->thread())
224 {
225 return;
226 }
227
228 // called by own thread, will deadlock, return
230 {
231 return;
232 }
233
234 QThread *workerThread = thread(); // must be before quit()
235 this->quit();
236
237 // T647, discussed here:
238 // https://discordapp.com/channels/539048679160676382/539925070550794240/573260844004016148
239 const unsigned long waitTimeoutMs = this->waitTimeoutMs();
240 const QString name(this->getName());
241 qint64 waitTime = QDateTime::currentMSecsSinceEpoch();
242 const bool ok = workerThread->wait(waitTimeoutMs);
243 waitTime = QDateTime::currentMSecsSinceEpoch() - waitTime;
244 const QString msg = QStringLiteral("Waiting for quitAndWait of '%1' for %2ms").arg(name).arg(waitTime);
245 const QByteArray msgBA = msg.toLatin1();
246 SWIFT_AUDIT_X(ok, Q_FUNC_INFO,
247 msgBA); // MS 2019-05 AUDIT because we want a stack trace of all threads, via breakpad
248 CLogMessage(this).info(msg);
249 Q_UNUSED(ok)
250 }
251
252 void CContinuousWorker::finish()
253 {
254 this->setFinished();
255
256 QThread *workerThread = this->thread();
257 Q_ASSERT_X(m_owner->thread()->isRunning(), Q_FUNC_INFO, "Owner thread's event loop already ended");
258
259 // MS 2018-09 Now we post the DeferredDelete event from within the worker thread, but rely on it being
260 // dispatched
261 // by the owner thread. Posted events are moved along with the object when moveToThread is called.
262 this->deleteLater();
263
264 this->moveToThread(
265 m_owner->thread()); // move worker back to the thread which constructed it, so there is no race on deletion
266 // must not access the worker beyond this point, as it now lives in the owner's thread and could be deleted at
267 // any moment
268
269 QMetaObject::invokeMethod(workerThread, [workerThread] {
270 // quit and wait is redundant as the CRegularThread dtor will do that anyway, but put here for debugging
271 workerThread->quit();
272 const bool ok = workerThread->wait(5000);
273 const QString as = QStringLiteral("Worker thread '%2' refuses to stop after worker finished")
274 .arg(workerThread->objectName());
275 const QByteArray asBA = as.toLatin1();
276 SWIFT_AUDIT_X(ok, Q_FUNC_INFO, asBA);
277
278 workerThread->deleteLater();
279 });
280 }
281} // namespace swift::misc
virtual void beforeQuit() noexcept
Called before quit is called.
Definition worker.h:363
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
static const QString & worker()
Background task.
Class for emitting a log message.
Definition logmessage.h:27
Derived & info(const char16_t(&format)[N])
Set the severity to info, providing a format string.
Just a subclass of QThread whose destructor waits for the thread to finish.
Definition worker.h:38
~CRegularThread()
Destructor.
Definition worker.cpp:34
static bool isInThisThread(const QObject *toBeTested)
Is the current thread the object's thread?
CWorkerBase()
Constructor.
Definition worker.cpp:127
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
void abandon() noexcept
Notify the task that its result is no longer needed, so it can finish early.
Definition worker.cpp:144
static const QStringList & getLogCategories()
Log categories.
Definition worker.cpp:131
void abandonAndWait() noexcept
Convenience to call abandon() followed by waitForFinished().
Definition worker.cpp:153
bool isAbandoned() const
For the task to check whether it can finish early.
Definition worker.cpp:162
bool hasStarted() const
True if the worker has started.
Definition worker.h:200
~CWorkerBase()
Destructor.
Definition worker.cpp:129
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
Free functions in swift::misc.
qint64 currentMSecsSinceEpoch()
const char * className() const const
bool invokeMethod(QObject *context, Functor &&function, Args &&... arguments)
QObject(QObject *parent)
QMetaObject::Connection connect(const QObject *sender, PointerToMemberFunction signal, Functor functor)
void deleteLater()
virtual const QMetaObject * metaObject() const const
bool moveToThread(QThread *targetThread)
void setObjectName(QAnyStringView name)
QThread * thread() const const
QString arg(Args &&... args) const const
bool isEmpty() const const
QByteArray toLatin1() const const
QThread * currentThread()
void finished()
bool isInterruptionRequested() const const
bool isRunning() const const
void quit()
void requestInterruption()
virtual void run()
void start(QThread::Priority priority)
void started()
bool wait(QDeadlineTimer deadline)
#define SWIFT_AUDIT_X(COND, WHERE, WHAT)
A weaker kind of verify.
Definition verify.h:38
#define SWIFT_VERIFY_X(COND, WHERE, WHAT)
A weaker kind of assert.
Definition verify.h:26