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