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

source code of qtbase/src/corelib/thread/qthread.cpp