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