Qt
Internal/Contributor docs for the Qt SDK. Note: These are NOT official API docs; those are found at https://doc.qt.io/
Loading...
Searching...
No Matches
qthread_win.cpp
Go to the documentation of this file.
1// Copyright (C) 2016 The Qt Company Ltd.
2// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
3// Qt-Security score:significant reason:default
4
5#include "qthread.h"
6#include "qthread_p.h"
7
9#include <private/qcoreapplication_p.h>
10#include <private/qeventdispatcher_win_p.h>
12#include "qmutex.h"
13#include <private/quniquehandle_types_p.h>
14#include <private/qwin32ticks_p.h>
15
16#include <QtCore/qspan.h>
17
18#include <qt_windows.h>
19
20#ifndef _MT
21# define _MT
22#endif // _MT
23#include <process.h>
24
25extern "C" {
26// MinGW is missing the declaration of SetThreadDescription:
27WINBASEAPI
28HRESULT
29WINAPI
30SetThreadDescription(
31 _In_ HANDLE hThread,
32 _In_ PCWSTR lpThreadDescription
33 );
34}
35
36#ifndef THREAD_POWER_THROTTLING_EXECUTION_SPEED
37#define THREAD_POWER_THROTTLING_EXECUTION_SPEED 0x1
38#define THREAD_POWER_THROTTLING_CURRENT_VERSION 1
39
44} THREAD_POWER_THROTTLING_STATE;
45#endif
46
47#ifndef CREATE_WAITABLE_TIMER_HIGH_RESOLUTION
48#define CREATE_WAITABLE_TIMER_HIGH_RESOLUTION 0x2
49#endif
50
51QT_BEGIN_NAMESPACE
52
53Q_STATIC_LOGGING_CATEGORY(lcQThread, "qt.core.thread", QtWarningMsg)
54
55#if QT_CONFIG(thread)
56
57Q_CONSTINIT static thread_local QThreadData *currentThreadData = nullptr;
58
59static void deref_current_thread_data(QThreadData *data);
60static void destroy_current_thread_data(void *p)
61{
62 QThreadData *data = static_cast<QThreadData *>(p);
63 QThread *thread = data->thread.loadAcquire();
64
65 if (data->isAdopted) {
66 // If this is an adopted thread, then QThreadData owns the QThread and
67 // this is very likely the last reference. These pointers cannot be
68 // null and there is no race.
69 QThreadPrivate *thread_p = static_cast<QThreadPrivate *>(QObjectPrivate::get(thread));
70 thread_p->finish();
71 } else {
72 // We may be racing the QThread destructor in another thread and it may
73 // have begun destruction; we must not dereference the QThread pointer.
74 }
75
76 deref_current_thread_data(data);
77}
78
79// static
80void deref_current_thread_data(QThreadData *data)
81{
82 // the QThread object may still have a reference, so this may not delete
83 data->deref();
84
85 // ... but we must reset it to zero before returning so we aren't
86 // leaving a dangling pointer.
87 currentThreadData = nullptr;
88}
89
90static QThreadData *get_thread_data()
91{
92 return currentThreadData;
93}
94
95static void set_thread_data(QThreadData *data) noexcept
96{
97 if (data) {
98 struct Cleanup {
99 Cleanup() { QThreadStoragePrivate::init(); }
100 ~Cleanup() { destroy_current_thread_data(currentThreadData); }
101 };
102 static thread_local Cleanup currentThreadCleanup;
103 }
104 currentThreadData = data;
105}
106
107/*
108 QThreadData
109*/
110void QThreadData::clearCurrentThreadData()
111{
112 set_thread_data(nullptr);
113}
114
115QThreadData *QThreadData::currentThreadData() noexcept
116{
117 return get_thread_data();
118}
119
120QThreadData *QThreadData::createCurrentThreadData()
121{
122 Q_ASSERT(!currentThreadData());
123
124 QThreadData *data = new QThreadData();
125
126 // This needs to be called prior to new QAdoptedThread() to avoid
127 // recursion (see qobject.cpp).
128 set_thread_data(data);
129
130 QT_TRY {
131 data->thread.storeRelease(new QAdoptedThread(data));
132 } QT_CATCH(...) {
133 deref_current_thread_data(data);
134 QT_RETHROW;
135 }
136 return data;
137}
138
139void QAdoptedThread::init()
140{
141 d_func()->handle = GetCurrentThread();
142}
143
144/**************************************************************************
145 ** QThreadPrivate
146 *************************************************************************/
147
148#endif // QT_CONFIG(thread)
149
150QAbstractEventDispatcher *QThreadPrivate::createEventDispatcher(QThreadData *data)
151{
152 Q_UNUSED(data);
153 return new QEventDispatcherWin32;
154}
155
156#if QT_CONFIG(thread)
157
158unsigned int __stdcall QT_ENSURE_STACK_ALIGNED_FOR_SSE QThreadPrivate::start(void *arg) noexcept
159{
160 QThread *thr = reinterpret_cast<QThread *>(arg);
161 QThreadData *data = QThreadData::get2(thr);
162
163 data->ref();
164 set_thread_data(data);
165 data->threadId.storeRelaxed(QThread::currentThreadId());
166
167 // If a QThread is restarted, reuse the QBindingStatus, too
168 data->reuseBindingStatusForNewNativeThread();
169
170 {
171 QMutexLocker locker(&thr->d_func()->mutex);
172 data->quitNow = thr->d_func()->exited;
173
174 if (thr->d_func()->serviceLevel != QThread::QualityOfService::Auto)
175 thr->d_func()->setQualityOfServiceLevel(thr->d_func()->serviceLevel);
176 }
177
178 data->ensureEventDispatcher();
179 data->eventDispatcher.loadRelaxed()->startingUp();
180
181 // sets the name of the current thread.
182 QString threadName = std::exchange(thr->d_func()->objectName, {});
183 if (Q_LIKELY(threadName.isEmpty()))
184 threadName = QString::fromUtf8(thr->metaObject()->className());
185 SetThreadDescription(GetCurrentThread(), reinterpret_cast<const wchar_t *>(threadName.utf16()));
186
187 emit thr->started(QThread::QPrivateSignal());
188 QThread::setTerminationEnabled(true);
189 thr->run();
190
191 thr->d_func()->finish();
192 return 0;
193}
194
195void QThreadPrivate::setQualityOfServiceLevel(QThread::QualityOfService qosLevel)
196{
197 Q_Q(QThread);
198 serviceLevel = qosLevel;
199
200#if (_WIN32_WINNT >= _WIN32_WINNT_WIN10_RS3)
201 qCDebug(lcQThread) << "Setting thread QoS class to" << qosLevel << "for thread" << q;
202
203 THREAD_POWER_THROTTLING_STATE state;
204 memset(&state, 0, sizeof(state));
205 state.Version = THREAD_POWER_THROTTLING_CURRENT_VERSION;
206
207 switch (qosLevel) {
208 case QThread::QualityOfService::Auto:
209 state.ControlMask = 0; // Unset control of QoS
210 state.StateMask = 0;
211 break;
212 case QThread::QualityOfService::Eco:
213 state.ControlMask = THREAD_POWER_THROTTLING_EXECUTION_SPEED;
214 state.StateMask = THREAD_POWER_THROTTLING_EXECUTION_SPEED;
215 break;
216 case QThread::QualityOfService::High:
217 state.ControlMask = THREAD_POWER_THROTTLING_EXECUTION_SPEED;
218 state.StateMask = 0; // Ask to disable throttling
219 break;
220 }
221 if (!SetThreadInformation(::GetCurrentThread(), THREAD_INFORMATION_CLASS::ThreadPowerThrottling,
222 &state, sizeof(state))) {
223 qErrnoWarning("Failed to set thread power throttling state");
224 }
225#endif
226}
227
228/*
229 For regularly terminating threads, this will be called and executed by the thread as the
230 last code before the thread exits. In that case, \a arg is the current QThread.
231
232 However, this function will also be called by QThread::terminate (as well as wait() and
233 setTerminationEnabled) to give Qt a chance to update the terminated thread's state and
234 process pending DeleteLater events for objects that live in the terminated thread. And for
235 adopted thread, this method is called by the thread watcher.
236
237 In those cases, \a arg will not be the current thread.
238*/
239void QThreadPrivate::finish(bool lockAnyway) noexcept
240{
241 QThreadPrivate *d = this;
242 QThread *thr = q_func();
243
244 QMutexLocker locker(lockAnyway ? &d->mutex : nullptr);
245 d->threadState = QThreadPrivate::Finishing;
246 d->priority = QThread::InheritPriority;
247 if (lockAnyway)
248 locker.unlock();
249 emit thr->finished(QThread::QPrivateSignal());
250 QCoreApplicationPrivate::sendPostedEvents(nullptr, QEvent::DeferredDelete, d->data);
251 QThreadStoragePrivate::finish(&d->data->tls);
252 if (lockAnyway)
253 locker.relock();
254
255 QAbstractEventDispatcher *eventDispatcher = d->data->eventDispatcher.loadRelaxed();
256 if (eventDispatcher) {
257 d->data->eventDispatcher = 0;
258 if (lockAnyway)
259 locker.unlock();
260 eventDispatcher->closingDown();
261 delete eventDispatcher;
262 if (lockAnyway)
263 locker.relock();
264 }
265
266 d->threadState = QThreadPrivate::Finished;
267 d->interruptionRequested.store(false, std::memory_order_relaxed);
268
269 if (!d->waiters) {
270 CloseHandle(d->handle);
271 d->handle = 0;
272 }
273}
274
275/**************************************************************************
276 ** QThread
277 *************************************************************************/
278
279Qt::HANDLE QThread::currentThreadIdImpl() noexcept
280{
281 return reinterpret_cast<Qt::HANDLE>(quintptr(GetCurrentThreadId()));
282}
283
284int QThread::idealThreadCount() noexcept
285{
286 // Since Windows 11 & Server 2022, the process defaults to affinity to all
287 // processor groups, even though each thread is limited to a specific
288 // processor group. Prior to that, the application starts with affinity to
289 // a specific group but the process becomes multi-group if the application
290 // changes any thread's affinity to another group.
291 //
292 // https://learn.microsoft.com/en-us/windows/win32/procthread/processor-groups#behavior-starting-with-windows-11-and-windows-server-2022
293 auto countArray = [](QSpan<const USHORT> groups) {
294 int total = 0;
295 for (USHORT group : groups)
296 total += GetActiveProcessorCount(group);
297 return total;
298 };
299
300 // Typical case: all but the largest systems will fit this array
301 // Note: this API has been around since Windows 7.
302 USHORT groups[16];
303 USHORT groupCount = std::size(groups);
304 if (Q_LIKELY(GetProcessGroupAffinity(HANDLE(-1), &groupCount, groups))) {
305 return countArray({ groups, groupCount });
306 } else if (groupCount > std::size(groups)) {
307 // use a larger buffer
308 auto buffer = static_cast<USHORT *>(alloca(sizeof(USHORT) * groupCount));
309 if (GetProcessGroupAffinity(HANDLE(-1), &groupCount, buffer))
310 return countArray({ buffer, groupCount });
311 }
312
313 // The new API failed, for some reason (it shouldn't have!). Fall back to
314 // the oldest of APIs. Note this may be limited to 64 logical processors.
315 SYSTEM_INFO sysinfo;
316 GetSystemInfo(&sysinfo);
317 return sysinfo.dwNumberOfProcessors;
318}
319
320void QThread::yieldCurrentThread()
321{
322 SwitchToThread();
323}
324
325#endif // QT_CONFIG(thread)
326
327void QThread::sleep(std::chrono::nanoseconds nsecs)
328{
329 using namespace std::chrono;
330 if (nsecs < 30ms) {
331 QUniqueWin32NullHandle waitableTimerHandle;
332 waitableTimerHandle.reset(CreateWaitableTimerEx(
333 nullptr, nullptr, CREATE_WAITABLE_TIMER_HIGH_RESOLUTION, TIMER_ALL_ACCESS));
334 if (waitableTimerHandle) {
335 using namespace std::chrono_literals;
336 // SetWaitableTimerEx's uses intervals of 100ns (0.1µs)
337 const auto ticks100ns = ceil<QtPrivate::win32_ticks>(nsecs);
338 LARGE_INTEGER i;
339 // Negate to make it a relative timeout:
340 i.QuadPart = std::min(-(ticks100ns.count()), -1ll);
341 BOOL timerResult = SetWaitableTimerEx(
342 waitableTimerHandle.get(), &i,
343 0, // not periodic
344 nullptr, nullptr, // no callback
345 nullptr, // no wake context / don't wake from sleep
346 0); // lowest tolerated delay
347
348 if (timerResult == TRUE) {
349 if (WaitForSingleObject(waitableTimerHandle.get(), INFINITE) == ERROR_SUCCESS)
350 return;
351 }
352 }
353 }
354 // Fallback:
355 ::Sleep(DWORD(ceil<milliseconds>(nsecs).count()));
356}
357
358void QThread::sleep(unsigned long secs)
359{
360 ::Sleep(secs * 1000);
361}
362
363void QThread::msleep(unsigned long msecs)
364{
365 ::Sleep(msecs);
366}
367
368void QThread::usleep(unsigned long usecs)
369{
370 sleep(std::chrono::microseconds(usecs));
371}
372
373#if QT_CONFIG(thread)
374
375void QThread::start(Priority priority)
376{
377 Q_D(QThread);
378 QMutexLocker locker(&d->mutex);
379
380 if (d->threadState == QThreadPrivate::Finishing) {
381 locker.unlock();
382 wait();
383 locker.relock();
384 }
385
386 if (d->threadState == QThreadPrivate::Running)
387 return;
388
389 // avoid interacting with the binding system
390 d->objectName = d->extraData ? d->extraData->objectName.valueBypassingBindings()
391 : QString();
392 d->threadState = QThreadPrivate::Running;
393 d->exited = false;
394 d->returnCode = 0;
395 d->interruptionRequested.store(false, std::memory_order_relaxed);
396
397 /*
398 NOTE: we create the thread in the suspended state, set the
399 priority and then resume the thread.
400
401 since threads are created with normal priority by default, we
402 could get into a case where a thread (with priority less than
403 NormalPriority) tries to create a new thread (also with priority
404 less than NormalPriority), but the newly created thread preempts
405 its 'parent' and runs at normal priority.
406 */
407#if defined(Q_CC_MSVC) && !defined(_DLL)
408 // MSVC -MT or -MTd build
409 d->handle = (Qt::HANDLE) _beginthreadex(NULL, d->stackSize, QThreadPrivate::start,
410 this, CREATE_SUSPENDED, nullptr);
411#else
412 // MSVC -MD or -MDd or MinGW build
413 d->handle = CreateThread(nullptr, d->stackSize,
414 reinterpret_cast<LPTHREAD_START_ROUTINE>(QThreadPrivate::start),
415 this, CREATE_SUSPENDED, nullptr);
416#endif
417
418 if (!d->handle) {
419 qErrnoWarning("QThread::start: Failed to create thread");
420 d->threadState = QThreadPrivate::NotStarted;
421 return;
422 }
423
424 int prio;
425 d->priority = priority;
426 switch (priority) {
427 case IdlePriority:
428 prio = THREAD_PRIORITY_IDLE;
429 break;
430
431 case LowestPriority:
432 prio = THREAD_PRIORITY_LOWEST;
433 break;
434
435 case LowPriority:
436 prio = THREAD_PRIORITY_BELOW_NORMAL;
437 break;
438
439 case NormalPriority:
440 prio = THREAD_PRIORITY_NORMAL;
441 break;
442
443 case HighPriority:
444 prio = THREAD_PRIORITY_ABOVE_NORMAL;
445 break;
446
447 case HighestPriority:
448 prio = THREAD_PRIORITY_HIGHEST;
449 break;
450
451 case TimeCriticalPriority:
452 prio = THREAD_PRIORITY_TIME_CRITICAL;
453 break;
454
455 case InheritPriority:
456 default:
457 prio = GetThreadPriority(GetCurrentThread());
458 break;
459 }
460
461 if (!SetThreadPriority(d->handle, prio)) {
462 qErrnoWarning("QThread::start: Failed to set thread priority");
463 }
464
465 if (ResumeThread(d->handle) == (DWORD) -1) {
466 qErrnoWarning("QThread::start: Failed to resume new thread");
467 }
468}
469
470void QThread::terminate()
471{
472 Q_D(QThread);
473 QMutexLocker locker(&d->mutex);
474 if (d->threadState != QThreadPrivate::Running)
475 return;
476 if (!d->terminationEnabled) {
477 d->terminatePending = true;
478 return;
479 }
480
481 TerminateThread(d->handle, 0);
482 d->finish(false);
483}
484
485bool QThreadPrivate::wait(QMutexLocker<QMutex> &locker, QDeadlineTimer deadline)
486{
487 Q_ASSERT(threadState != QThreadPrivate::Finished);
488 Q_ASSERT(locker.isLocked());
489 QThreadPrivate *d = this;
490
491 ++d->waiters;
492 locker.mutex()->unlock();
493
494 bool ret = false;
495 switch (WaitForSingleObject(d->handle, deadline.remainingTime())) {
496 case WAIT_OBJECT_0:
497 ret = true;
498 break;
499 case WAIT_FAILED:
500 qErrnoWarning("QThread::wait: Thread wait failure");
501 break;
502 case WAIT_ABANDONED:
503 case WAIT_TIMEOUT:
504 default:
505 break;
506 }
507
508 locker.mutex()->lock();
509 --d->waiters;
510
511 if (ret && d->threadState < QThreadPrivate::Finished) {
512 // thread was terminated by someone else
513
514 d->finish(false);
515 }
516
517 if (d->threadState == QThreadPrivate::Finished && !d->waiters) {
518 CloseHandle(d->handle);
519 d->handle = 0;
520 }
521
522 return ret;
523}
524
525void QThread::setTerminationEnabled(bool enabled)
526{
527 QThreadData *thr = QThreadData::currentThreadData();
528 Q_ASSERT_X(thr && !thr->isAdopted, "QThread::setTerminationEnabled()",
529 "Current thread was not started with QThread.");
530 QThreadPrivate *d = thr->thread.loadRelaxed()->d_func();
531 QMutexLocker locker(&d->mutex);
532 d->terminationEnabled = enabled;
533 if (enabled && d->terminatePending) {
534 d->finish(false);
535 locker.unlock(); // don't leave the mutex locked!
536 _endthreadex(0);
537 }
538}
539
540// Caller must hold the mutex
541void QThreadPrivate::setPriority(QThread::Priority threadPriority)
542{
543 // copied from start() with a few modifications:
544
545 int prio;
546 priority = threadPriority;
547 switch (threadPriority) {
548 case QThread::IdlePriority:
549 prio = THREAD_PRIORITY_IDLE;
550 break;
551
552 case QThread::LowestPriority:
553 prio = THREAD_PRIORITY_LOWEST;
554 break;
555
556 case QThread::LowPriority:
557 prio = THREAD_PRIORITY_BELOW_NORMAL;
558 break;
559
560 case QThread::NormalPriority:
561 prio = THREAD_PRIORITY_NORMAL;
562 break;
563
564 case QThread::HighPriority:
565 prio = THREAD_PRIORITY_ABOVE_NORMAL;
566 break;
567
568 case QThread::HighestPriority:
569 prio = THREAD_PRIORITY_HIGHEST;
570 break;
571
572 case QThread::TimeCriticalPriority:
573 prio = THREAD_PRIORITY_TIME_CRITICAL;
574 break;
575
576 default:
577 return;
578 }
579
580 if (!SetThreadPriority(handle, prio)) {
581 qErrnoWarning("QThread::setPriority: Failed to set thread priority");
582 }
583}
584
585#endif // QT_CONFIG(thread)
586
587QT_END_NAMESPACE
static QAbstractEventDispatcher * createEventDispatcher(QThreadData *data)
#define Q_STATIC_LOGGING_CATEGORY(name,...)
#define CREATE_WAITABLE_TIMER_HIGH_RESOLUTION