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.cpp
Go to the documentation of this file.
1// Copyright (C) 2016 The Qt Company Ltd.
2// Copyright (C) 2016 Intel Corporation.
3// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
4// Qt-Security score:significant reason:default
5
6#include "qthread.h"
7#include "qthread_p.h"
8
11#include "private/qcoreapplication_p.h"
12#include "qeventloop.h"
13#include "qmutex.h"
14
16
17using namespace Qt::StringLiterals;
18
19/*
20 QPostEventList
21*/
22
24{
25 int priority = ev.priority;
26 if (isEmpty() ||
27 constLast().priority >= priority ||
28 insertionOffset >= size()) {
29 // optimization: we can simply append if the last event in
30 // the queue has higher or equal priority
31 append(ev);
32 } else {
33 // insert event in descending priority order, using upper
34 // bound for a given priority (to ensure proper ordering
35 // of events with the same priority)
36 QPostEventList::iterator at = std::upper_bound(begin() + insertionOffset, end(), ev);
37 insert(at, ev);
38 }
39}
40
41
42/*
43 QThreadData
44*/
45
47{
48#if QT_CONFIG(thread)
49 Q_ASSERT(_ref.loadRelaxed() == 0);
50#endif
51
52 if (threadId.loadAcquire() == QCoreApplicationPrivate::theMainThreadId.loadAcquire()) {
53 QCoreApplicationPrivate::theMainThread.storeRelease(nullptr);
54 QCoreApplicationPrivate::theMainThreadId.storeRelaxed(nullptr);
56 }
57
58 // ~QThread() sets thread to nullptr, so if it isn't null here, it's
59 // because we're being run before the main object itself. This can only
60 // happen for QAdoptedThread. Note that both ~QThreadPrivate() and
61 // ~QObjectPrivate() will deref this object again, but that is acceptable
62 // because this destructor is still running (the _ref sub-object has not
63 // been destroyed) and there's no reentrancy. The refcount will become
64 // negative, but that's acceptable.
65 QThread *t = thread.loadAcquire();
66 thread.storeRelease(nullptr);
67 delete t;
68
70
71 // fprintf(stderr, "QThreadData %p destroyed\n", this);
72}
73
75{
76 // ~QEvent() may run arbitrary code, including code that posts new events, so drain in
77 // passes; cap them so a destructor that always posts cannot loop forever.
78 constexpr int MaxPasses = 16;
79
80 QList<QPostEvent> pending;
81 for (int pass = 0;; ++pass) {
82 {
83 const auto locker = qt_scoped_lock(postEventList.mutex);
84 if (postEventList.isEmpty())
85 return;
86 pending.swap(static_cast<QList<QPostEvent> &>(postEventList));
87 postEventList.startOffset = 0;
88 postEventList.insertionOffset = 0;
89 }
90
91 // unpost them all first: ~QObject and ~QEvent would otherwise come looking for
92 // these events in the list we have already swapped out
93 for (const QPostEvent &pe : std::as_const(pending)) {
94 if (!pe.event) // already dispatched: pe.receiver may be dangling
95 continue;
96 pe.receiver->d_func()->postedEvents.fetchAndSubRelaxed(1);
97 pe.event->m_posted = false;
98 }
99
100 if (pass == MaxPasses) {
101 qWarning("QThreadData::clearEvents: giving up after %d passes, leaking %lld event(s)",
102 MaxPasses, qlonglong(pending.size()));
103 return;
104 }
105
106 // may run arbitrary code (virtual ~QEvent()), so do it last:
107 for (const QPostEvent &pe : std::as_const(pending))
108 delete pe.event;
109 pending.clear();
110 }
111}
112
113QAbstractEventDispatcher *QThreadData::createEventDispatcher()
114{
115 QAbstractEventDispatcher *ed = QThreadPrivate::createEventDispatcher(this);
116 eventDispatcher.storeRelease(ed);
117 return ed;
118}
119
120/*
121 QAdoptedThread
122*/
123
124QAdoptedThread::QAdoptedThread(QThreadData *data)
125 : QThread(*new QThreadPrivate(data))
126{
127 // avoid a cyclic reference count: QThreadData owns this QAdoptedThread
128 // object but QObject's constructor increased the count
129 data->deref();
130
131 data->isAdopted = true;
132 Qt::HANDLE id = QThread::currentThreadId();
133 data->threadId.storeRelaxed(id);
134 if (!QCoreApplicationPrivate::theMainThreadId.loadAcquire()) {
135 // we are the main thread
136 QCoreApplicationPrivate::theMainThread.storeRelease(this);
137 QCoreApplicationPrivate::theMainThreadId.storeRelaxed(id);
138
139 // bypass the bindings because nothing can be listening yet
140 d_func()->setObjectNameWithoutBindings(u"Qt mainThread"_s);
141 }
142
143 // thread should be running and not finished for the lifetime
144 // of the application (even if QCoreApplication goes away)
145#if QT_CONFIG(thread)
146 d_func()->threadState = QThreadPrivate::Running;
147 init();
148 {
149 QMutexLocker lock(&d_func()->mutex);
150 d_func()->data->m_statusOrPendingObjects.setStatusAndClearList(
151 QtPrivate::getBindingStatus({}));
152 }
153#endif
154 // fprintf(stderr, "new QAdoptedThread = %p\n", this);
155}
156
158{
159 // fprintf(stderr, "~QAdoptedThread = %p\n", this);
160}
161
162#if QT_CONFIG(thread)
163void QAdoptedThread::run()
164{
165 // this function should never be called
166 qFatal("QAdoptedThread::run(): Internal error, this implementation should never be called.");
167}
168#endif
169
170#if QT_CONFIG(thread)
171/*
172 QThreadPrivate
173*/
174
175QThreadPrivate::QThreadPrivate(QThreadData *d)
176 : QObjectPrivate(), data(d)
177{
178
179// INTEGRITY doesn't support self-extending stack. The default stack size for
180// a pthread on INTEGRITY is too small so we have to increase the default size
181// to 128K.
182#ifdef Q_OS_INTEGRITY
183 stackSize = 128 * 1024;
184#elif defined(Q_OS_RTEMS)
185 Q_CONSTINIT static bool envStackSizeOk = false;
186 static const int envStackSize = qEnvironmentVariableIntValue("QT_DEFAULT_THREAD_STACK_SIZE", &envStackSizeOk);
187 if (envStackSizeOk)
188 stackSize = envStackSize;
189#endif
190
191 if (!data)
192 data = new QThreadData;
193}
194
195QThreadPrivate::~QThreadPrivate()
196{
197 // access to m_statusOrPendingObjects cannot race with anything
198 // unless there is already a potential use-after-free bug, as the
199 // thread is in the process of being destroyed
200 delete data->m_statusOrPendingObjects.list();
201 data->clearEvents();
202 data->deref();
203}
204
205/*!
206 \class QThread
207 \inmodule QtCore
208 \brief The QThread class provides a platform-independent way to
209 manage threads.
210
211 \ingroup thread
212
213 A QThread object manages one thread of control within the
214 program. QThreads begin executing in run(). By default, run() starts the
215 event loop by calling exec() and runs a Qt event loop inside the thread.
216
217 You can use worker objects by moving them to the thread using
218 QObject::moveToThread().
219
220 \snippet code/src_corelib_thread_qthread.cpp worker
221
222 The code inside the Worker's slot would then execute in a
223 separate thread. However, you are free to connect the
224 Worker's slots to any signal, from any object, in any thread. It
225 is safe to connect signals and slots across different threads,
226 thanks to a mechanism called \l{Qt::QueuedConnection}{queued
227 connections}.
228
229 Another way to make code run in a separate thread, is to subclass QThread
230 and reimplement run(). For example:
231
232 \snippet code/src_corelib_thread_qthread.cpp reimpl-run
233
234 In that example, the thread will exit after the run function has returned.
235 There will not be any event loop running in the thread unless you call
236 exec().
237
238 It is important to remember that a QThread instance \l{QObject#Thread
239 Affinity}{lives in} the old thread that instantiated it, not in the
240 new thread that calls run(). This means that all of QThread's queued
241 slots and \l {QMetaObject::invokeMethod()}{invoked methods} will execute
242 in the old thread. Thus, a developer who wishes to invoke slots in the
243 new thread must use the worker-object approach; new slots should not be
244 implemented directly into a subclassed QThread.
245
246 Unlike queued slots or invoked methods, methods called directly on the
247 QThread object will execute in the thread that calls the method. When
248 subclassing QThread, keep in mind that the constructor executes in the
249 old thread while run() executes in the new thread. If a member variable
250 is accessed from both functions, then the variable is accessed from two
251 different threads. Check that it is safe to do so.
252
253 \note Care must be taken when interacting with objects across different
254 threads. As a general rule, functions can only be called from the thread
255 that created the QThread object itself (e.g. setPriority()), unless the
256 documentation says otherwise. See \l{Synchronizing Threads} for details.
257
258 \section1 Managing Threads
259
260 QThread will notify you via a signal when the thread is
261 started() and finished(), or you can use isFinished() and
262 isRunning() to query the state of the thread.
263
264 You can stop the thread by calling exit() or quit(). In extreme
265 cases, you may want to forcibly terminate() an executing thread.
266 However, doing so is dangerous and discouraged. Please read the
267 documentation for terminate() and setTerminationEnabled() for
268 detailed information.
269
270 You often want to deallocate objects that live in a thread when
271 a thread ends. To do this, connect the finished() signal to
272 QObject::deleteLater().
273
274 Use wait() to block the calling thread, until the other thread
275 has finished execution (or until a specified time has passed).
276
277 QThread also provides static, platform independent sleep
278 functions: sleep(), msleep(), and usleep() allow full second,
279 millisecond, and microsecond resolution respectively.
280
281 \note wait() and the sleep() functions should be unnecessary in
282 general, since Qt is an event-driven framework. Instead of
283 wait(), consider listening for the finished() signal. Instead of
284 the sleep() functions, consider using QChronoTimer.
285
286 The static functions currentThreadId() and currentThread() return
287 identifiers for the currently executing thread. The former
288 returns a platform specific ID for the thread; the latter returns
289 a QThread pointer.
290
291 To choose the name that your thread will be given (as identified
292 by the command \c{ps -L} on Linux, for example), you can call
293 \l{QObject::setObjectName()}{setObjectName()} before starting the thread.
294 If you don't call \l{QObject::setObjectName()}{setObjectName()},
295 the name given to your thread will be the class name of the runtime
296 type of your thread object (for example, \c "RenderThread" in the case of the
297 \l{Mandelbrot} example, as that is the name of the QThread subclass).
298 Note that this is currently not available with release builds on Windows.
299
300 \sa {Multi-threading in Qt}, QThreadStorage, {Synchronizing Threads},
301 Mandelbrot, {Producer and Consumer using Semaphores},
302 {Producer and Consumer using Wait Conditions}
303*/
304
305/*!
306 \fn Qt::HANDLE QThread::currentThreadId()
307
308 Returns the thread handle of the currently executing thread.
309
310 \warning The handle returned by this function is used for internal
311 purposes and should not be used in any application code.
312
313 \note On Windows, this function returns the DWORD (Windows-Thread
314 ID) returned by the Win32 function GetCurrentThreadId(), not the pseudo-HANDLE
315 (Windows-Thread HANDLE) returned by the Win32 function GetCurrentThread().
316*/
317
318/*!
319 \fn int QThread::idealThreadCount()
320
321 Returns the ideal number of threads that this process can run in parallel.
322 This is done by querying the number of logical processors available to this
323 process (if supported by this OS) or the total number of logical processors
324 in the system. This function returns 1 if neither value could be
325 determined.
326
327 \note On operating systems that support setting a thread's affinity to a
328 subset of all logical processors, the value returned by this function may
329 change between threads and over time.
330
331 \note On operating systems that support CPU hotplugging and hot-unplugging,
332 the value returned by this function may also change over time (and note
333 that CPUs can be turned on and off by software, without a physical,
334 hardware change).
335*/
336
337/*!
338 \fn void QThread::yieldCurrentThread()
339
340 Yields execution of the current thread to another runnable thread,
341 if any. Note that the operating system decides to which thread to
342 switch.
343*/
344
345/*!
346 \fn void QThread::start(Priority priority)
347
348 Begins execution of the thread by calling run(). The
349 operating system will schedule the thread according to the \a
350 priority parameter. If the thread is already running, this
351 function does nothing.
352
353 The effect of the \a priority parameter is dependent on the
354 operating system's scheduling policy. In particular, the \a priority
355 will be ignored on systems that do not support thread priorities
356 (such as on Linux, see the
357 \l {http://linux.die.net/man/2/sched_setscheduler}{sched_setscheduler}
358 documentation for more details).
359
360 \sa run(), terminate()
361*/
362
363/*!
364 \fn void QThread::started()
365
366 This signal is emitted from the associated thread when it starts executing,
367 so any slots connected to it may be called via queued invocation. Whilst
368 the event may have been posted before run() is called, any
369 \l {Signals and Slots Across Threads} {cross-thread delivery} of the signal
370 may still be pending.
371
372 \sa run(), finished()
373*/
374
375/*!
376 \fn void QThread::finished()
377
378 This signal is emitted from the associated thread right before it finishes executing.
379
380 When this signal is emitted, the event loop has already stopped running.
381 No more events will be processed in the thread, except for deferred deletion events.
382 This signal can be connected to QObject::deleteLater(), to free objects in that thread.
383
384 \note If the associated thread was terminated using terminate(), it is undefined from
385 which thread this signal is emitted.
386
387 \sa started()
388*/
389
390/*!
391 \enum QThread::Priority
392
393 This enum type indicates how the operating system should schedule
394 newly created threads.
395
396 \value IdlePriority scheduled only when no other threads are
397 running.
398
399 \value LowestPriority scheduled less often than LowPriority.
400 \value LowPriority scheduled less often than NormalPriority.
401
402 \value NormalPriority the default priority of the operating
403 system.
404
405 \value HighPriority scheduled more often than NormalPriority.
406 \value HighestPriority scheduled more often than HighPriority.
407
408 \value TimeCriticalPriority scheduled as often as possible.
409
410 \value InheritPriority use the same priority as the creating
411 thread. This is the default.
412*/
413
414/*!
415 Returns a pointer to a QThread which manages the currently
416 executing thread. This function never returns a null pointer.
417*/
418QThread *QThread::currentThread()
419{
420 QThreadData *data = QThreadData::current();
421 Q_ASSERT(data != nullptr);
422 return data->thread.loadAcquire();
423}
424
425/*!
426 \since 6.8
427
428 Returns whether the currently executing thread is the main thread.
429
430 The main thread is the thread in which QCoreApplication was created.
431 This is usually the thread that called the \c{main()} function, but not necessarily so.
432 It is the thread that is processing the GUI events and in which graphical objects
433 (QWindow, QWidget) can be created.
434
435 \sa currentThread(), QCoreApplication::instance()
436*/
437bool QThread::isMainThread() noexcept
438{
439 return currentThreadId() == QCoreApplicationPrivate::theMainThreadId.loadRelaxed();
440}
441
442/*!
443 Constructs a new QThread to manage a new thread. The \a parent
444 takes ownership of the QThread. The thread does not begin
445 executing until start() is called.
446
447 \sa start()
448*/
449QThread::QThread(QObject *parent)
450 : QObject(*(new QThreadPrivate), parent)
451{
452 Q_D(QThread);
453 // fprintf(stderr, "QThreadData %p created for thread %p\n", d->data, this);
454 d->data->thread.storeRelaxed(this);
455}
456
457/*!
458 \internal
459 */
460QThread::QThread(QThreadPrivate &dd, QObject *parent)
461 : QObject(dd, parent)
462{
463 Q_D(QThread);
464 // fprintf(stderr, "QThreadData %p taken from private data for thread %p\n", d->data, this);
465 d->data->thread.storeRelaxed(this);
466}
467
468/*!
469 Destroys the QThread.
470
471 Note that deleting a QThread object will not stop the execution
472 of the thread it manages. Deleting a running QThread (i.e.
473 isFinished() returns \c false) will result in a program
474 crash. Wait for the finished() signal before deleting the
475 QThread.
476
477 Since Qt 6.3, it is allowed to delete a QThread instance created by
478 a call to QThread::create() even if the corresponding thread is
479 still running. In such a case, Qt will post an interruption request
480 to that thread (via requestInterruption()); will ask the thread's
481 event loop (if any) to quit (via quit()); and will block until the
482 thread has finished.
483
484 \sa create(), isInterruptionRequested(), exec(), quit()
485*/
486QThread::~QThread()
487{
488 Q_D(QThread);
489 {
490 QMutexLocker locker(&d->mutex);
491 if (d->threadState == QThreadPrivate::Finishing)
492 d->wait(locker, QDeadlineTimer::Forever);
493 if (d->threadState == QThreadPrivate::Running && !d->data->isAdopted)
494 qFatal("QThread: Destroyed while thread '%ls' is still running", qUtf16Printable(objectName()));
495
496 d->data->thread.storeRelease(nullptr);
497 }
498}
499
500/*!
501 \threadsafe
502 Returns \c true if the thread is finished; otherwise returns \c false.
503
504 A thread is considered finished if it has returned from the run() function
505 and the finished() signal has been emitted.
506
507//! [execution-after-finished]
508 Note the thread may still run for arbitrary amount of time after the
509 finished() signal is emitted, running clean-up operations such as executing
510 the destructors to \c{thread_local} variables. To synchronize with all
511 effects from the thread, call wait() and verify it returned true.
512//! [execution-after-finished]
513
514 \sa isRunning()
515*/
516bool QThread::isFinished() const
517{
518 Q_D(const QThread);
519 QMutexLocker locker(&d->mutex);
520 return d->threadState >= QThreadPrivate::Finishing;
521}
522
523/*!
524 \threadsafe
525 Returns \c true if the thread is running; otherwise returns \c false.
526
527 A thread is considered to be running if QThread has been started with
528 start() but is not yet finished.
529
530 \include qthread.cpp execution-after-finished
531
532 \sa isFinished()
533*/
534bool QThread::isRunning() const
535{
536 Q_D(const QThread);
537 QMutexLocker locker(&d->mutex);
538 return d->threadState == QThreadPrivate::Running;
539}
540
541/*!
542 Sets the stack size for the thread to \a stackSize bytes. If \a stackSize
543 is zero, the operating system or runtime will choose a default value.
544 Otherwise, the thread's stack size will be the value provided (which may be
545 rounded up or down).
546
547 On most operating systems, the amount of memory allocated to serve the
548 stack will initially be smaller than \a stackSize and will grow as the
549 thread uses the stack. This parameter sets the maximum size it will be
550 allowed to grow to (that is, it sets the size of the virtual memory space
551 the stack is allowed to occupy).
552
553 This function can only be called before the thread is started.
554
555 \warning Most operating systems place minimum and maximum limits
556 on thread stack sizes. The thread will fail to start if the stack
557 size is outside these limits.
558
559 \sa stackSize()
560*/
561void QThread::setStackSize(uint stackSize)
562{
563 Q_D(QThread);
564 Q_ASSERT_X(!isRunning(), "QThread::setStackSize",
565 "cannot change stack size while the thread is running");
566 QMutexLocker locker(&d->mutex);
567 d->stackSize = stackSize;
568}
569
570/*!
571 Returns the maximum stack size for the thread in bytes (if set with
572 setStackSize()); otherwise returns zero.
573
574 \sa setStackSize()
575*/
576uint QThread::stackSize() const
577{
578 Q_D(const QThread);
579 QMutexLocker locker(&d->mutex);
580 return d->stackSize;
581}
582
583/*!
584 \enum QThread::QualityOfService
585 \since 6.9
586
587 This enum describes the quality of service level of a thread, and provides
588 the scheduler with information about the kind of work that the thread
589 performs. On platforms with different CPU profiles, or with the ability to
590 clock certain cores of a CPU down, this allows the scheduler to select or
591 configure a CPU core with suitable performance and energy characteristics
592 for the thread.
593
594 \value Auto The default value, leaving it to the scheduler to decide which
595 CPU core to run the thread on.
596 \value High The scheduler should run this thread to a high-performance CPU
597 core.
598 \value Eco The scheduler should run this thread to an energy-efficient CPU
599 core.
600
601 \sa Priority, serviceLevel(), QThreadPool::serviceLevel()
602*/
603
604/*!
605 \since 6.9
606
607 Set the Quality of Service level of the thread object to \a serviceLevel.
608 This can only be called from the thread itself or before the thread is
609 started!
610
611 This is currently only implemented on Apple platforms, and Windows.
612 The function call will complete successfully on other platforms but will
613 not currently have any effect.
614
615 \sa serviceLevel(), QThreadPool::setServiceLevel()
616*/
617void QThread::setServiceLevel(QualityOfService serviceLevel)
618{
619 Q_D(QThread);
620 QMutexLocker locker(&d->mutex);
621 if (d->threadState != QThreadPrivate::Running) {
622 d->serviceLevel = serviceLevel;
623 } else {
624 Q_ASSERT_X(isCurrentThread(), "QThread::setServiceLevel",
625 "cannot change quality of service level of a separate, running, thread");
626 d->setQualityOfServiceLevel(serviceLevel);
627 }
628}
629
630/*!
631 \since 6.9
632
633 Return the current Quality of Service level of the thread.
634
635 \sa setServiceLevel(), QThreadPool::serviceLevel()
636*/
637QThread::QualityOfService QThread::serviceLevel() const
638{
639 Q_D(const QThread);
640 QMutexLocker locker(&d->mutex);
641 return d->serviceLevel;
642}
643
644#endif
645
646/*!
647 \internal
648 Transitions BindingStatusOrList to the binding status state. If we had a list of
649 pending objects, all objects get their reinitBindingStorageAfterThreadMove method
650 called, and afterwards, the list gets discarded.
651 */
652void QtPrivate::BindingStatusOrList::setStatusAndClearList(QBindingStatus *status) noexcept
653{
654 if (auto pendingObjects = list()) {
655 for (auto obj: *pendingObjects)
656 QObjectPrivate::get(obj)->reinitBindingStorageAfterThreadMove();
657 delete pendingObjects;
658 }
659 // synchronizes-with the load-acquire in bindingStatus():
660 data.store(encodeBindingStatus(status), std::memory_order_release);
661}
662
663#if QT_CONFIG(thread)
664
665/*!
666 Enters the event loop and waits until exit() is called, returning the value
667 that was passed to exit(). The value returned is 0 if exit() is called via
668 quit().
669
670 This function is meant to be called from within run(). It is necessary to
671 call this function to start event handling.
672
673 \note This can only be called within the thread itself, i.e. when
674 it is the current thread.
675
676 \sa quit(), exit()
677*/
678int QThread::exec()
679{
680 Q_D(QThread);
681 const auto status = QtPrivate::getBindingStatus(QtPrivate::QBindingStatusAccessToken{});
682
683 QMutexLocker locker(&d->mutex);
684 d->data->m_statusOrPendingObjects.setStatusAndClearList(status);
685 d->data->quitNow = false;
686 if (d->exited) {
687 d->exited = false;
688 return d->returnCode;
689 }
690 locker.unlock();
691
692 QEventLoop eventLoop;
693 int returnCode = eventLoop.exec();
694
695 locker.relock();
696 d->exited = false;
697 d->returnCode = -1;
698 return returnCode;
699}
700
701
702/*!
703 \internal
704 If BindingStatusOrList is already in the binding status state, this will
705 return that BindingStatus pointer.
706 Otherwise, \a object is added to the list, and we return nullptr.
707 The list is allocated if it does not already exist.
708 */
709QBindingStatus *QtPrivate::BindingStatusOrList::addObjectUnlessAlreadyStatus(QObject *object)
710{
711 if (auto status = bindingStatus())
712 return status;
713 List *objectList = list();
714 if (!objectList) {
715 objectList = new List();
716 objectList->reserve(8);
717 data.store(encodeList(objectList), std::memory_order_relaxed);
718 }
719 objectList->push_back(object);
720 return nullptr;
721}
722
723/*!
724 \internal
725 If BindingStatusOrList is a list, remove \a object from it
726 */
727void QtPrivate::BindingStatusOrList::removeObject(QObject *object)
728{
729 List *objectList = list();
730 if (!objectList)
731 return;
732 auto it = std::remove(objectList->begin(), objectList->end(), object);
733 objectList->erase(it, objectList->end());
734}
735
736QBindingStatus *QThreadPrivate::addObjectWithPendingBindingStatusChange(QObject *obj)
737{
738 if (auto status = data->m_statusOrPendingObjects.bindingStatus())
739 return status;
740 QMutexLocker lock(&mutex);
741 return data->m_statusOrPendingObjects.addObjectUnlessAlreadyStatus(obj);
742}
743
744void QThreadPrivate::removeObjectWithPendingBindingStatusChange(QObject *obj)
745{
746 if (data->m_statusOrPendingObjects.bindingStatus())
747 return;
748 QMutexLocker lock(&mutex);
749 data->m_statusOrPendingObjects.removeObject(obj);
750}
751
752
753/*!
754 \threadsafe
755 Tells the thread's event loop to exit with a return code.
756
757 After calling this function, the thread leaves the event loop and
758 returns from the call to QEventLoop::exec(). The
759 QEventLoop::exec() function returns \a returnCode.
760
761 By convention, a \a returnCode of 0 means success, any non-zero value
762 indicates an error.
763
764 Note that unlike the C library function of the same name, this
765 function \e does return to the caller -- it is event processing
766 that stops.
767
768 No QEventLoops will be started anymore in this thread until
769 QThread::exec() has been called again. If the eventloop in QThread::exec()
770 is not running then the next call to QThread::exec() will also return
771 immediately.
772
773 \sa quit(), QEventLoop
774*/
775void QThread::exit(int returnCode)
776{
777 Q_D(QThread);
778 QMutexLocker locker(&d->mutex);
779 d->exited = true;
780 d->returnCode = returnCode;
781 d->data->quitNow = true;
782 for (int i = 0; i < d->data->eventLoops.size(); ++i) {
783 QEventLoop *eventLoop = d->data->eventLoops.at(i);
784 eventLoop->exit(returnCode);
785 }
786}
787
788/*!
789 \threadsafe
790 Tells the thread's event loop to exit with return code 0 (success).
791 Equivalent to calling QThread::exit(0).
792
793 This function does nothing if the thread does not have an event
794 loop.
795
796 \sa exit(), QEventLoop
797*/
798void QThread::quit()
799{ exit(); }
800
801/*!
802 The starting point for the thread. After calling start(), the
803 newly created thread calls this function. The default
804 implementation simply calls exec().
805
806 You can reimplement this function to facilitate advanced thread
807 management. Returning from this method will end the execution of
808 the thread.
809
810 \sa start(), wait()
811*/
812void QThread::run()
813{
814 (void) exec();
815}
816
817/*! \fn void QThread::setPriority(Priority priority)
818 \since 4.1
819
820 This function sets the \a priority for a running thread. If the
821 thread is not running, this function does nothing and returns
822 immediately. Use start() to start a thread with a specific
823 priority.
824
825 The \a priority argument can be any value in the \c
826 QThread::Priority enum except for \c InheritPriority.
827
828 The effect of the \a priority parameter is dependent on the
829 operating system's scheduling policy. In particular, the \a priority
830 will be ignored on systems that do not support thread priorities
831 (such as on Linux, see http://linux.die.net/man/2/sched_setscheduler
832 for more details).
833
834 \sa Priority, priority(), start()
835*/
836void QThread::setPriority(Priority priority)
837{
838 if (priority == QThread::InheritPriority) {
839 qWarning("QThread::setPriority: Argument cannot be InheritPriority");
840 return;
841 }
842 Q_D(QThread);
843 QMutexLocker locker(&d->mutex);
844 if (d->threadState != QThreadPrivate::Running) {
845 qWarning("QThread::setPriority: Cannot set priority, thread is not running");
846 return;
847 }
848 d->setPriority(priority);
849}
850
851/*!
852 \since 4.1
853
854 Returns the priority for a running thread. If the thread is not
855 running, this function returns \c InheritPriority.
856
857 \sa Priority, setPriority(), start()
858*/
859QThread::Priority QThread::priority() const
860{
861 Q_D(const QThread);
862 QMutexLocker locker(&d->mutex);
863
864 // mask off the high bits that are used for flags
865 return Priority(d->priority & 0xffff);
866}
867
868/*!
869 \fn void QThread::sleep(std::chrono::nanoseconds nsecs)
870 \since 6.6
871
872 Forces the current thread to sleep for \a nsecs.
873
874 Avoid using this function if you need to wait for a given condition to
875 change. Instead, connect a slot to the signal that indicates the change or
876 use an event handler (see \l QObject::event()).
877
878 \note This function does not guarantee accuracy. The application may sleep
879 longer than \a nsecs under heavy load conditions.
880*/
881
882/*!
883 \fn void QThread::sleep(unsigned long secs)
884
885 Forces the current thread to sleep for \a secs seconds.
886
887 This is an overloaded function, equivalent to calling:
888 \code
889 QThread::sleep(std::chrono::seconds{secs});
890 \endcode
891
892 \sa msleep(), usleep()
893*/
894
895/*!
896 \fn void QThread::msleep(unsigned long msecs)
897
898 This is an overloaded function, equivalent to calling:
899 \code
900 QThread::sleep(std::chrono::milliseconds{msecs});
901 \endcode
902
903 \note This function does not guarantee accuracy. The application may sleep
904 longer than \a msecs under heavy load conditions. Some OSes might round \a
905 msecs up to 10 ms or 15 ms.
906
907 \sa sleep(), usleep()
908*/
909
910/*!
911 \fn void QThread::usleep(unsigned long usecs)
912
913 This is an overloaded function, equivalent to calling:
914 \code
915 QThread::sleep(std::chrono::microseconds{secs});
916 \endcode
917
918 \note This function does not guarantee accuracy. The application may sleep
919 longer than \a usecs under heavy load conditions. Some OSes might round \a
920 usecs up to 10 ms or 15 ms; on Windows, it will be rounded up to a multiple
921 of 1 ms.
922
923 \sa sleep(), msleep()
924*/
925
926/*!
927 \fn void QThread::terminate()
928 \threadsafe
929
930 Terminates the execution of the thread. The thread may or may not
931 be terminated immediately, depending on the operating system's
932 scheduling policies. Use QThread::wait() after terminate(), to be
933 sure.
934
935 When the thread is terminated, all threads waiting for the thread
936 to finish will be woken up.
937
938 \warning This function is dangerous and its use is discouraged.
939 The thread can be terminated at any point in its code path.
940 Threads can be terminated while modifying data. There is no
941 chance for the thread to clean up after itself, unlock any held
942 mutexes, etc. In short, use this function only if absolutely
943 necessary.
944
945 Termination can be explicitly enabled or disabled by calling
946 QThread::setTerminationEnabled(). Calling this function while
947 termination is disabled results in the termination being
948 deferred, until termination is re-enabled. See the documentation
949 of QThread::setTerminationEnabled() for more information.
950
951 \sa setTerminationEnabled()
952*/
953
954/*!
955 \fn bool QThread::wait(QDeadlineTimer deadline)
956 \since 5.15
957
958 Blocks the thread until either of these conditions is met:
959
960 \list
961 \li The thread associated with this QThread object has finished
962 execution (i.e. when it returns from \l{run()}). This function
963 will return true if the thread has finished. It also returns
964 true if the thread has not been started yet.
965 \li The \a deadline is reached. This function will return false if the
966 deadline is reached.
967 \endlist
968
969 A deadline timer set to \c QDeadlineTimer::Forever (the default) will never
970 time out: in this case, the function only returns when the thread returns
971 from \l{run()} or if the thread has not yet started.
972
973 This provides similar functionality to the POSIX \c
974 pthread_join() function.
975
976 \note On some operating systems, this function may return true while the
977 operating system thread is still running and may be executing clean-up code
978 such as C++11 \c{thread_local} destructors. Operating systems where this
979 function only returns true after the OS thread has fully exited include
980 Linux, Windows, and Apple operating systems.
981
982 \sa sleep(), terminate()
983*/
984bool QThread::wait(QDeadlineTimer deadline)
985{
986 Q_D(QThread);
987 QMutexLocker locker(&d->mutex);
988
989 if (d->threadState == QThreadPrivate::NotStarted || d->threadState == QThreadPrivate::Finished)
990 return true;
991 if (isCurrentThread()) {
992 qWarning("QThread::wait: Thread tried to wait on itself");
993 return false;
994 }
995 return d->wait(locker, deadline);
996}
997
998/*!
999 \fn void QThread::setTerminationEnabled(bool enabled)
1000
1001 Enables or disables termination of the current thread based on the
1002 \a enabled parameter. The thread must have been started by
1003 QThread.
1004
1005 When \a enabled is false, termination is disabled. Future calls
1006 to QThread::terminate() will return immediately without effect.
1007 Instead, the termination is deferred until termination is enabled.
1008
1009 When \a enabled is true, termination is enabled. Future calls to
1010 QThread::terminate() will terminate the thread normally. If
1011 termination has been deferred (i.e. QThread::terminate() was
1012 called with termination disabled), this function will terminate
1013 the calling thread \e immediately. Note that this function will
1014 not return in this case.
1015
1016 \sa terminate()
1017*/
1018
1019/*!
1020 \since 5.5
1021 Returns the current event loop level for the thread.
1022
1023 \note This can only be called within the thread itself, i.e. when
1024 it is the current thread.
1025*/
1026
1027int QThread::loopLevel() const
1028{
1029 Q_D(const QThread);
1030 return d->data->eventLoops.size();
1031}
1032
1033/*!
1034 \internal
1035 Returns the thread handle of this thread.
1036 It can be compared with the return value of currentThreadId().
1037
1038 This is used to implement isCurrentThread, and might be useful
1039 for debugging (e.g. by comparing the value in gdb with info threads).
1040
1041 \note Thread handles of destroyed threads might be reused by the
1042 operating system. Storing the return value of this function can
1043 therefore give surprising results if it outlives the QThread object
1044 (threads claimed to be the same even if they aren't).
1045*/
1046Qt::HANDLE QThreadPrivate::threadId() const noexcept
1047{
1048 return data->threadId.loadRelaxed();
1049}
1050
1051/*!
1052 \since 6.8
1053 Returns true if this thread is QThread::currentThread.
1054
1055 \sa currentThreadId()
1056*/
1057bool QThread::isCurrentThread() const noexcept
1058{
1059 Q_D(const QThread);
1060 return QThread::currentThreadId() == d->threadId();
1061}
1062
1063#else // QT_CONFIG(thread)
1064
1065QThread::QThread(QObject *parent)
1066 : QObject(*(new QThreadPrivate), parent)
1067{
1068 Q_D(QThread);
1069 d->data->thread.storeRelaxed(this);
1070}
1071
1072QThread::~QThread()
1073{
1074
1075}
1076
1077QThread *QThread::createThreadImpl(std::future<void>&&)
1078{
1079 return nullptr;
1080}
1081
1082void QThread::run()
1083{
1084
1085}
1086
1087int QThread::exec()
1088{
1089 return 0;
1090}
1091
1092void QThread::start(Priority priority)
1093{
1094 Q_D(QThread);
1095 Q_UNUSED(priority);
1096 d->running = true;
1097}
1098
1099void QThread::terminate()
1100{
1101
1102}
1103
1104void QThread::quit()
1105{
1106
1107}
1108
1109void QThread::exit(int returnCode)
1110{
1111 Q_D(QThread);
1112 d->data->quitNow = true;
1113 for (int i = 0; i < d->data->eventLoops.size(); ++i) {
1114 QEventLoop *eventLoop = d->data->eventLoops.at(i);
1115 eventLoop->exit(returnCode);
1116 }
1117}
1118
1119bool QThread::wait(QDeadlineTimer deadline)
1120{
1121 Q_UNUSED(deadline);
1122 return false;
1123}
1124
1125bool QThread::event(QEvent *event)
1126{
1127 return QObject::event(event);
1128}
1129
1130Qt::HANDLE QThread::currentThreadIdImpl() noexcept
1131{
1132 return Qt::HANDLE(currentThread());
1133}
1134
1135QThread *QThread::currentThread()
1136{
1137 return QThreadData::current()->thread.loadAcquire();
1138}
1139
1140bool QThread::isMainThread() noexcept
1141{
1142 return true;
1143}
1144
1145bool QThread::isCurrentThread() const noexcept
1146{
1147 return true;
1148}
1149
1150int QThread::idealThreadCount() noexcept
1151{
1152 return 1;
1153}
1154
1155void QThread::yieldCurrentThread()
1156{
1157
1158}
1159
1160bool QThread::isFinished() const
1161{
1162 return false;
1163}
1164
1165bool QThread::isRunning() const
1166{
1167 Q_D(const QThread);
1168 return d->running;
1169}
1170
1171void QThread::requestInterruption()
1172{
1173
1174}
1175
1176bool QThread::isInterruptionRequested() const
1177{
1178 return false;
1179}
1180
1181void QThread::setTerminationEnabled(bool)
1182{
1183}
1184
1185void QThread::setServiceLevel(QualityOfService)
1186{
1187}
1188
1189// No threads: so we can just use static variables
1190Q_CONSTINIT static QThreadData *data = nullptr;
1191
1192QThreadData *QThreadData::currentThreadData() noexcept
1193{
1194 return data;
1195}
1196
1197QThreadData *QThreadData::createCurrentThreadData()
1198{
1199 Q_ASSERT(!currentThreadData());
1200 data = new QThreadData;
1201 data->thread = new QAdoptedThread(data);
1202 return data;
1203}
1204
1206{
1207 delete data;
1208 data = 0;
1209}
1210
1211/*!
1212 \internal
1213 */
1214QThread::QThread(QThreadPrivate &dd, QObject *parent)
1215 : QObject(dd, parent)
1216{
1217 Q_D(QThread);
1218 // fprintf(stderr, "QThreadData %p taken from private data for thread %p\n", d->data, this);
1219 d->data->thread.storeRelaxed(this);
1220}
1221
1225
1227{
1228 data->thread.storeRelease(nullptr); // prevent QThreadData from deleting the QThreadPrivate (again).
1229 delete data;
1230}
1231
1232void QThread::setStackSize(uint stackSize)
1233{
1234 Q_UNUSED(stackSize);
1235}
1236
1237uint QThread::stackSize() const
1238{
1239 return 0;
1240}
1241
1242#endif // QT_CONFIG(thread)
1243
1244/*!
1245 \since 5.0
1246
1247 Returns a pointer to the event dispatcher object for the thread. If no event
1248 dispatcher exists for the thread, this function returns \nullptr.
1249*/
1250QAbstractEventDispatcher *QThread::eventDispatcher() const
1251{
1252 Q_D(const QThread);
1253 return d->data->eventDispatcher.loadRelaxed();
1254}
1255
1256/*!
1257 \since 5.0
1258
1259 Sets the event dispatcher for the thread to \a eventDispatcher. This is
1260 only possible as long as there is no event dispatcher installed for the
1261 thread yet.
1262
1263 An event dispatcher is automatically created for the main thread when \l
1264 QCoreApplication is instantiated and on start() for auxiliary threads.
1265
1266 This method takes ownership of the object.
1267*/
1268void QThread::setEventDispatcher(QAbstractEventDispatcher *eventDispatcher)
1269{
1270 Q_D(QThread);
1271 if (d->data->hasEventDispatcher()) {
1272 qWarning("QThread::setEventDispatcher: An event dispatcher has already been created for this thread");
1273 } else {
1274 eventDispatcher->moveToThread(this);
1275 if (eventDispatcher->thread() == this) // was the move successful?
1276 d->data->eventDispatcher.storeRelaxed(eventDispatcher);
1277 else
1278 qWarning("QThread::setEventDispatcher: Could not move event dispatcher to target thread");
1279 }
1280}
1281
1282/*!
1283 \fn bool QThread::wait(unsigned long time)
1284
1285 \overload
1286 \a time is the time to wait in milliseconds.
1287 If \a time is ULONG_MAX, then the wait will never timeout.
1288*/
1289
1290#if QT_CONFIG(thread)
1291
1292/*!
1293 \reimp
1294*/
1295bool QThread::event(QEvent *event)
1296{
1297 if (event->type() == QEvent::Quit) {
1298 quit();
1299 return true;
1300 } else {
1301 return QObject::event(event);
1302 }
1303}
1304
1305/*!
1306 \since 5.2
1307 \threadsafe
1308
1309 Request the interruption of the thread.
1310 That request is advisory and it is up to code running on the thread to decide
1311 if and how it should act upon such request.
1312 This function does not stop any event loop running on the thread and
1313 does not terminate it in any way.
1314
1315 This function has no effect on the main thread, and does nothing if the thread
1316 is not currently running.
1317
1318 \sa isInterruptionRequested()
1319*/
1320
1321void QThread::requestInterruption()
1322{
1323 Q_D(QThread);
1324 if (d->threadId() == QCoreApplicationPrivate::theMainThreadId.loadAcquire()) {
1325 qWarning("QThread::requestInterruption has no effect on the main thread");
1326 return;
1327 }
1328 QMutexLocker locker(&d->mutex);
1329 if (d->threadState != QThreadPrivate::Running)
1330 return;
1331 d->interruptionRequested.store(true, std::memory_order_relaxed);
1332}
1333
1334/*!
1335 \since 5.2
1336
1337 Return true if the task running on this thread should be stopped.
1338 An interruption can be requested by requestInterruption().
1339
1340 This function can be used to make long running tasks cleanly interruptible.
1341 Never checking or acting on the value returned by this function is safe,
1342 however it is advisable do so regularly in long running functions.
1343 Take care not to call it too often, to keep the overhead low.
1344
1345 \code
1346 void long_task() {
1347 forever {
1348 if ( QThread::currentThread()->isInterruptionRequested() ) {
1349 return;
1350 }
1351 }
1352 }
1353 \endcode
1354
1355 \note This can only be called within the thread itself, i.e. when
1356 it is the current thread.
1357
1358 \sa currentThread(), requestInterruption()
1359*/
1360bool QThread::isInterruptionRequested() const
1361{
1362 Q_D(const QThread);
1363 // fast path: check that the flag is not set:
1364 if (!d->interruptionRequested.load(std::memory_order_relaxed))
1365 return false;
1366 // slow path: if the flag is set, take into account run status:
1367 QMutexLocker locker(&d->mutex);
1368 return d->threadState == QThreadPrivate::Running;
1369}
1370
1371/*!
1372 \fn template <typename Function, typename... Args> QThread *QThread::create(Function &&f, Args &&... args)
1373 \since 5.10
1374
1375 Creates a new QThread object that will execute the function \a f with the
1376 arguments \a args.
1377
1378 The new thread is not started -- it must be started by an explicit call
1379 to start(). This allows you to connect to its signals, move QObjects
1380 to the thread, choose the new thread's priority and so on. The function
1381 \a f will be called in the new thread.
1382
1383 Returns the newly created QThread instance.
1384
1385 \note the caller acquires ownership of the returned QThread instance.
1386
1387 \warning do not call start() on the returned QThread instance more than once;
1388 doing so will result in undefined behavior.
1389
1390 \sa start()
1391*/
1392
1393class QThreadCreateThread : public QThread
1394{
1395public:
1396 explicit QThreadCreateThread(std::future<void> &&future)
1397 : m_future(std::move(future))
1398 {
1399 }
1400
1401 ~QThreadCreateThread()
1402 {
1403 requestInterruption();
1404 quit();
1405 wait();
1406 }
1407
1408private:
1409 void run() override
1410 {
1411 m_future.get();
1412 }
1413
1414 std::future<void> m_future;
1415};
1416
1417QThread *QThread::createThreadImpl(std::future<void> &&future)
1418{
1419 return new QThreadCreateThread(std::move(future));
1420}
1421
1422/*!
1423 \class QDaemonThread
1424 \since 5.5
1425 \brief The QDaemonThread provides a class to manage threads that outlive QCoreApplication
1426 \internal
1427
1428 Note: don't try to deliver events from the started() signal.
1429*/
1430QDaemonThread::QDaemonThread(QObject *parent)
1431 : QThread(parent)
1432{
1433 // QThread::started() is emitted from the thread we start
1434 connect(this, &QThread::started,
1435 this,
1436 [](){ QThreadData::current()->requiresCoreApplication = false; },
1437 Qt::DirectConnection);
1438}
1439
1440QDaemonThread::~QDaemonThread()
1441{
1442}
1443
1444#endif // QT_CONFIG(thread)
1445
1446QT_END_NAMESPACE
1447
1448#include "moc_qthread.cpp"
void addEvent(const QPostEvent &ev)
Definition qthread.cpp:23
int priority
Definition qthread_p.h:46
void deref()
Definition qthread_p.h:346
static void clearCurrentThreadData()
Definition qthread.cpp:1205
bool isAdopted
Definition qthread_p.h:392
void clearEvents()
Definition qthread.cpp:74
QAbstractEventDispatcher * createEventDispatcher()
Definition qthread.cpp:113
static QAbstractEventDispatcher * createEventDispatcher(QThreadData *data)
QThreadPrivate(QThreadData *d=nullptr)
Definition qthread.cpp:1222
QThreadData * data
Definition qthread_p.h:292
Combined button and popup list for selecting options.