1/****************************************************************************
2**
3** Copyright (C) 2016 The Qt Company Ltd.
4** Copyright (C) 2016 Intel Corporation.
5** Contact: https://www.qt.io/licensing/
6**
7** This file is part of the QtCore module of the Qt Toolkit.
8**
9** $QT_BEGIN_LICENSE:LGPL$
10** Commercial License Usage
11** Licensees holding valid commercial Qt licenses may use this file in
12** accordance with the commercial license agreement provided with the
13** Software or, alternatively, in accordance with the terms contained in
14** a written agreement between you and The Qt Company. For licensing terms
15** and conditions see https://www.qt.io/terms-conditions. For further
16** information use the contact form at https://www.qt.io/contact-us.
17**
18** GNU Lesser General Public License Usage
19** Alternatively, this file may be used under the terms of the GNU Lesser
20** General Public License version 3 as published by the Free Software
21** Foundation and appearing in the file LICENSE.LGPL3 included in the
22** packaging of this file. Please review the following information to
23** ensure the GNU Lesser General Public License version 3 requirements
24** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
25**
26** GNU General Public License Usage
27** Alternatively, this file may be used under the terms of the GNU
28** General Public License version 2.0 or (at your option) the GNU General
29** Public license version 3 or any later version approved by the KDE Free
30** Qt Foundation. The licenses are as published by the Free Software
31** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
32** included in the packaging of this file. Please review the following
33** information to ensure the GNU General Public License requirements will
34** be met: https://www.gnu.org/licenses/gpl-2.0.html and
35** https://www.gnu.org/licenses/gpl-3.0.html.
36**
37** $QT_END_LICENSE$
38**
39****************************************************************************/
40
41#include "qthread.h"
42#include "qthreadstorage.h"
43#include "qmutex.h"
44#include "qreadwritelock.h"
45#include "qabstracteventdispatcher.h"
46
47#include <qeventloop.h>
48
49#include "qthread_p.h"
50#include "private/qcoreapplication_p.h"
51
52#include <limits>
53
54QT_BEGIN_NAMESPACE
55
56/*
57 QThreadData
58*/
59
60QThreadData::QThreadData(int initialRefCount)
61 : _ref(initialRefCount), loopLevel(0), scopeLevel(0),
62 eventDispatcher(nullptr),
63 quitNow(false), canWait(true), isAdopted(false), requiresCoreApplication(true)
64{
65 // fprintf(stderr, "QThreadData %p created\n", this);
66}
67
68QThreadData::~QThreadData()
69{
70#if QT_CONFIG(thread)
71 Q_ASSERT(_ref.loadRelaxed() == 0);
72#endif
73
74 // In the odd case that Qt is running on a secondary thread, the main
75 // thread instance will have been dereffed asunder because of the deref in
76 // QThreadData::current() and the deref in the pthread_destroy. To avoid
77 // crashing during QCoreApplicationData's global static cleanup we need to
78 // safeguard the main thread here.. This fix is a bit crude, but it solves
79 // the problem...
80 if (this->thread.loadAcquire() == QCoreApplicationPrivate::theMainThread.loadAcquire()) {
81 QCoreApplicationPrivate::theMainThread.storeRelease(nullptr);
82 QThreadData::clearCurrentThreadData();
83 }
84
85 // ~QThread() sets thread to nullptr, so if it isn't null here, it's
86 // because we're being run before the main object itself. This can only
87 // happen for QAdoptedThread. Note that both ~QThreadPrivate() and
88 // ~QObjectPrivate() will deref this object again, but that is acceptable
89 // because this destructor is still running (the _ref sub-object has not
90 // been destroyed) and there's no reentrancy. The refcount will become
91 // negative, but that's acceptable.
92 QThread *t = thread.loadAcquire();
93 thread.storeRelease(nullptr);
94 delete t;
95
96 for (int i = 0; i < postEventList.size(); ++i) {
97 const QPostEvent &pe = postEventList.at(i);
98 if (pe.event) {
99 --pe.receiver->d_func()->postedEvents;
100 pe.event->posted = false;
101 delete pe.event;
102 }
103 }
104
105 // fprintf(stderr, "QThreadData %p destroyed\n", this);
106}
107
108void QThreadData::ref()
109{
110#if QT_CONFIG(thread)
111 (void) _ref.ref();
112 Q_ASSERT(_ref.loadRelaxed() != 0);
113#endif
114}
115
116void QThreadData::deref()
117{
118#if QT_CONFIG(thread)
119 if (!_ref.deref())
120 delete this;
121#endif
122}
123
124QAbstractEventDispatcher *QThreadData::createEventDispatcher()
125{
126 QAbstractEventDispatcher *ed = QThreadPrivate::createEventDispatcher(this);
127 eventDispatcher.storeRelease(ed);
128 ed->startingUp();
129 return ed;
130}
131
132/*
133 QAdoptedThread
134*/
135
136QAdoptedThread::QAdoptedThread(QThreadData *data)
137 : QThread(*new QThreadPrivate(data))
138{
139 // thread should be running and not finished for the lifetime
140 // of the application (even if QCoreApplication goes away)
141#if QT_CONFIG(thread)
142 d_func()->running = true;
143 d_func()->finished = false;
144 init();
145#endif
146
147 // fprintf(stderr, "new QAdoptedThread = %p\n", this);
148}
149
150QAdoptedThread::~QAdoptedThread()
151{
152 // fprintf(stderr, "~QAdoptedThread = %p\n", this);
153}
154
155#if QT_CONFIG(thread)
156void QAdoptedThread::run()
157{
158 // this function should never be called
159 qFatal("QAdoptedThread::run(): Internal error, this implementation should never be called.");
160}
161
162/*
163 QThreadPrivate
164*/
165
166QThreadPrivate::QThreadPrivate(QThreadData *d)
167 : QObjectPrivate(), running(false), finished(false),
168 isInFinish(false), interruptionRequested(false),
169 exited(false), returnCode(-1),
170 stackSize(0), priority(QThread::InheritPriority), data(d)
171{
172
173// INTEGRITY doesn't support self-extending stack. The default stack size for
174// a pthread on INTEGRITY is too small so we have to increase the default size
175// to 128K.
176#ifdef Q_OS_INTEGRITY
177 stackSize = 128 * 1024;
178#elif defined(Q_OS_RTEMS)
179 static bool envStackSizeOk = false;
180 static const int envStackSize = qEnvironmentVariableIntValue("QT_DEFAULT_THREAD_STACK_SIZE", &envStackSizeOk);
181 if (envStackSizeOk)
182 stackSize = envStackSize;
183#endif
184
185#if defined (Q_OS_WIN)
186 handle = 0;
187 id = 0;
188 waiters = 0;
189 terminationEnabled = true;
190 terminatePending = false;
191#endif
192
193 if (!data)
194 data = new QThreadData;
195}
196
197QThreadPrivate::~QThreadPrivate()
198{
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 notifiy 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 From Qt 4.8 onwards, it is possible to deallocate objects that
268 live in a thread that has just ended, by connecting the
269 finished() signal to 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. These
277 functions were made public in Qt 5.0.
278
279 \note wait() and the sleep() functions should be unnecessary in
280 general, since Qt is an event-driven framework. Instead of
281 wait(), consider listening for the finished() signal. Instead of
282 the sleep() functions, consider using QTimer.
283
284 The static functions currentThreadId() and currentThread() return
285 identifiers for the currently executing thread. The former
286 returns a platform specific ID for the thread; the latter returns
287 a QThread pointer.
288
289 To choose the name that your thread will be given (as identified
290 by the command \c{ps -L} on Linux, for example), you can call
291 \l{QObject::setObjectName()}{setObjectName()} before starting the thread.
292 If you don't call \l{QObject::setObjectName()}{setObjectName()},
293 the name given to your thread will be the class name of the runtime
294 type of your thread object (for example, \c "RenderThread" in the case of the
295 \l{Mandelbrot Example}, as that is the name of the QThread subclass).
296 Note that this is currently not available with release builds on Windows.
297
298 \sa {Thread Support in Qt}, QThreadStorage, {Synchronizing Threads},
299 {Mandelbrot Example}, {Semaphores Example}, {Wait Conditions Example}
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 can be run on the system. This is done querying
319 the number of processor cores, both real and logical, in the system. This function returns 1
320 if the number of processor cores could not be detected.
321*/
322
323/*!
324 \fn void QThread::yieldCurrentThread()
325
326 Yields execution of the current thread to another runnable thread,
327 if any. Note that the operating system decides to which thread to
328 switch.
329*/
330
331/*!
332 \fn void QThread::start(Priority priority)
333
334 Begins execution of the thread by calling run(). The
335 operating system will schedule the thread according to the \a
336 priority parameter. If the thread is already running, this
337 function does nothing.
338
339 The effect of the \a priority parameter is dependent on the
340 operating system's scheduling policy. In particular, the \a priority
341 will be ignored on systems that do not support thread priorities
342 (such as on Linux, see the
343 \l {http://linux.die.net/man/2/sched_setscheduler}{sched_setscheduler}
344 documentation for more details).
345
346 \sa run(), terminate()
347*/
348
349/*!
350 \fn void QThread::started()
351
352 This signal is emitted from the associated thread when it starts executing,
353 before the run() function is called.
354
355 \sa finished()
356*/
357
358/*!
359 \fn void QThread::finished()
360
361 This signal is emitted from the associated thread right before it finishes executing.
362
363 When this signal is emitted, the event loop has already stopped running.
364 No more events will be processed in the thread, except for deferred deletion events.
365 This signal can be connected to QObject::deleteLater(), to free objects in that thread.
366
367 \note If the associated thread was terminated using terminate(), it is undefined from
368 which thread this signal is emitted.
369
370 \sa started()
371*/
372
373/*!
374 \enum QThread::Priority
375
376 This enum type indicates how the operating system should schedule
377 newly created threads.
378
379 \value IdlePriority scheduled only when no other threads are
380 running.
381
382 \value LowestPriority scheduled less often than LowPriority.
383 \value LowPriority scheduled less often than NormalPriority.
384
385 \value NormalPriority the default priority of the operating
386 system.
387
388 \value HighPriority scheduled more often than NormalPriority.
389 \value HighestPriority scheduled more often than HighPriority.
390
391 \value TimeCriticalPriority scheduled as often as possible.
392
393 \value InheritPriority use the same priority as the creating
394 thread. This is the default.
395*/
396
397/*!
398 Returns a pointer to a QThread which manages the currently
399 executing thread.
400*/
401QThread *QThread::currentThread()
402{
403 QThreadData *data = QThreadData::current();
404 Q_ASSERT(data != nullptr);
405 return data->thread.loadAcquire();
406}
407
408/*!
409 Constructs a new QThread to manage a new thread. The \a parent
410 takes ownership of the QThread. The thread does not begin
411 executing until start() is called.
412
413 \sa start()
414*/
415QThread::QThread(QObject *parent)
416 : QObject(*(new QThreadPrivate), parent)
417{
418 Q_D(QThread);
419 // fprintf(stderr, "QThreadData %p created for thread %p\n", d->data, this);
420 d->data->thread.storeRelaxed(this);
421}
422
423/*!
424 \internal
425 */
426QThread::QThread(QThreadPrivate &dd, QObject *parent)
427 : QObject(dd, parent)
428{
429 Q_D(QThread);
430 // fprintf(stderr, "QThreadData %p taken from private data for thread %p\n", d->data, this);
431 d->data->thread.storeRelaxed(this);
432}
433
434/*!
435 Destroys the QThread.
436
437 Note that deleting a QThread object will not stop the execution
438 of the thread it manages. Deleting a running QThread (i.e.
439 isFinished() returns \c false) will result in a program
440 crash. Wait for the finished() signal before deleting the
441 QThread.
442*/
443QThread::~QThread()
444{
445 Q_D(QThread);
446 {
447 QMutexLocker locker(&d->mutex);
448 if (d->isInFinish) {
449 locker.unlock();
450 wait();
451 locker.relock();
452 }
453 if (d->running && !d->finished && !d->data->isAdopted)
454 qFatal("QThread: Destroyed while thread is still running");
455
456 d->data->thread.storeRelease(nullptr);
457 }
458}
459
460/*!
461 \threadsafe
462 Returns \c true if the thread is finished; otherwise returns \c false.
463
464 \sa isRunning()
465*/
466bool QThread::isFinished() const
467{
468 Q_D(const QThread);
469 QMutexLocker locker(&d->mutex);
470 return d->finished || d->isInFinish;
471}
472
473/*!
474 \threadsafe
475 Returns \c true if the thread is running; otherwise returns \c false.
476
477 \sa isFinished()
478*/
479bool QThread::isRunning() const
480{
481 Q_D(const QThread);
482 QMutexLocker locker(&d->mutex);
483 return d->running && !d->isInFinish;
484}
485
486/*!
487 Sets the maximum stack size for the thread to \a stackSize. If \a
488 stackSize is greater than zero, the maximum stack size is set to
489 \a stackSize bytes, otherwise the maximum stack size is
490 automatically determined by the operating system.
491
492 \warning Most operating systems place minimum and maximum limits
493 on thread stack sizes. The thread will fail to start if the stack
494 size is outside these limits.
495
496 \sa stackSize()
497*/
498void QThread::setStackSize(uint stackSize)
499{
500 Q_D(QThread);
501 QMutexLocker locker(&d->mutex);
502 Q_ASSERT_X(!d->running, "QThread::setStackSize",
503 "cannot change stack size while the thread is running");
504 d->stackSize = stackSize;
505}
506
507/*!
508 Returns the maximum stack size for the thread (if set with
509 setStackSize()); otherwise returns zero.
510
511 \sa setStackSize()
512*/
513uint QThread::stackSize() const
514{
515 Q_D(const QThread);
516 QMutexLocker locker(&d->mutex);
517 return d->stackSize;
518}
519
520/*!
521 Enters the event loop and waits until exit() is called, returning the value
522 that was passed to exit(). The value returned is 0 if exit() is called via
523 quit().
524
525 This function is meant to be called from within run(). It is necessary to
526 call this function to start event handling.
527
528 \note This can only be called within the thread itself, i.e. when
529 it is the current thread.
530
531 \sa quit(), exit()
532*/
533int QThread::exec()
534{
535 Q_D(QThread);
536 QMutexLocker locker(&d->mutex);
537 d->data->quitNow = false;
538 if (d->exited) {
539 d->exited = false;
540 return d->returnCode;
541 }
542 locker.unlock();
543
544 QEventLoop eventLoop;
545 int returnCode = eventLoop.exec();
546
547 locker.relock();
548 d->exited = false;
549 d->returnCode = -1;
550 return returnCode;
551}
552
553/*!
554 \threadsafe
555 Tells the thread's event loop to exit with a return code.
556
557 After calling this function, the thread leaves the event loop and
558 returns from the call to QEventLoop::exec(). The
559 QEventLoop::exec() function returns \a returnCode.
560
561 By convention, a \a returnCode of 0 means success, any non-zero value
562 indicates an error.
563
564 Note that unlike the C library function of the same name, this
565 function \e does return to the caller -- it is event processing
566 that stops.
567
568 No QEventLoops will be started anymore in this thread until
569 QThread::exec() has been called again. If the eventloop in QThread::exec()
570 is not running then the next call to QThread::exec() will also return
571 immediately.
572
573 \sa quit(), QEventLoop
574*/
575void QThread::exit(int returnCode)
576{
577 Q_D(QThread);
578 QMutexLocker locker(&d->mutex);
579 d->exited = true;
580 d->returnCode = returnCode;
581 d->data->quitNow = true;
582 for (int i = 0; i < d->data->eventLoops.size(); ++i) {
583 QEventLoop *eventLoop = d->data->eventLoops.at(i);
584 eventLoop->exit(returnCode);
585 }
586}
587
588/*!
589 \threadsafe
590 Tells the thread's event loop to exit with return code 0 (success).
591 Equivalent to calling QThread::exit(0).
592
593 This function does nothing if the thread does not have an event
594 loop.
595
596 \sa exit(), QEventLoop
597*/
598void QThread::quit()
599{ exit(); }
600
601/*!
602 The starting point for the thread. After calling start(), the
603 newly created thread calls this function. The default
604 implementation simply calls exec().
605
606 You can reimplement this function to facilitate advanced thread
607 management. Returning from this method will end the execution of
608 the thread.
609
610 \sa start(), wait()
611*/
612void QThread::run()
613{
614 (void) exec();
615}
616
617/*! \fn void QThread::setPriority(Priority priority)
618 \since 4.1
619
620 This function sets the \a priority for a running thread. If the
621 thread is not running, this function does nothing and returns
622 immediately. Use start() to start a thread with a specific
623 priority.
624
625 The \a priority argument can be any value in the \c
626 QThread::Priority enum except for \c InheritPriority.
627
628 The effect of the \a priority parameter is dependent on the
629 operating system's scheduling policy. In particular, the \a priority
630 will be ignored on systems that do not support thread priorities
631 (such as on Linux, see http://linux.die.net/man/2/sched_setscheduler
632 for more details).
633
634 \sa Priority, priority(), start()
635*/
636void QThread::setPriority(Priority priority)
637{
638 if (priority == QThread::InheritPriority) {
639 qWarning("QThread::setPriority: Argument cannot be InheritPriority");
640 return;
641 }
642 Q_D(QThread);
643 QMutexLocker locker(&d->mutex);
644 if (!d->running) {
645 qWarning("QThread::setPriority: Cannot set priority, thread is not running");
646 return;
647 }
648 d->setPriority(priority);
649}
650
651/*!
652 \since 4.1
653
654 Returns the priority for a running thread. If the thread is not
655 running, this function returns \c InheritPriority.
656
657 \sa Priority, setPriority(), start()
658*/
659QThread::Priority QThread::priority() const
660{
661 Q_D(const QThread);
662 QMutexLocker locker(&d->mutex);
663
664 // mask off the high bits that are used for flags
665 return Priority(d->priority & 0xffff);
666}
667
668/*!
669 \fn void QThread::sleep(unsigned long secs)
670
671 Forces the current thread to sleep for \a secs seconds.
672
673 Avoid using this function if you need to wait for a given condition to
674 change. Instead, connect a slot to the signal that indicates the change or
675 use an event handler (see \l QObject::event()).
676
677 \note This function does not guarantee accuracy. The application may sleep
678 longer than \a secs under heavy load conditions.
679
680 \sa msleep(), usleep()
681*/
682
683/*!
684 \fn void QThread::msleep(unsigned long msecs)
685
686 Forces the current thread to sleep for \a msecs milliseconds.
687
688 Avoid using this function if you need to wait for a given condition to
689 change. Instead, connect a slot to the signal that indicates the change or
690 use an event handler (see \l QObject::event()).
691
692 \note This function does not guarantee accuracy. The application may sleep
693 longer than \a msecs under heavy load conditions. Some OSes might round \a
694 msecs up to 10 ms or 15 ms.
695
696 \sa sleep(), usleep()
697*/
698
699/*!
700 \fn void QThread::usleep(unsigned long usecs)
701
702 Forces the current thread to sleep for \a usecs microseconds.
703
704 Avoid using this function if you need to wait for a given condition to
705 change. Instead, connect a slot to the signal that indicates the change or
706 use an event handler (see \l QObject::event()).
707
708 \note This function does not guarantee accuracy. The application may sleep
709 longer than \a usecs under heavy load conditions. Some OSes might round \a
710 usecs up to 10 ms or 15 ms; on Windows, it will be rounded up to a multiple
711 of 1 ms.
712
713 \sa sleep(), msleep()
714*/
715
716/*!
717 \fn void QThread::terminate()
718 \threadsafe
719
720 Terminates the execution of the thread. The thread may or may not
721 be terminated immediately, depending on the operating system's
722 scheduling policies. Use QThread::wait() after terminate(), to be
723 sure.
724
725 When the thread is terminated, all threads waiting for the thread
726 to finish will be woken up.
727
728 \warning This function is dangerous and its use is discouraged.
729 The thread can be terminated at any point in its code path.
730 Threads can be terminated while modifying data. There is no
731 chance for the thread to clean up after itself, unlock any held
732 mutexes, etc. In short, use this function only if absolutely
733 necessary.
734
735 Termination can be explicitly enabled or disabled by calling
736 QThread::setTerminationEnabled(). Calling this function while
737 termination is disabled results in the termination being
738 deferred, until termination is re-enabled. See the documentation
739 of QThread::setTerminationEnabled() for more information.
740
741 \sa setTerminationEnabled()
742*/
743
744/*!
745 \fn bool QThread::wait(QDeadlineTimer deadline)
746 \since 5.15
747
748 Blocks the thread until either of these conditions is met:
749
750 \list
751 \li The thread associated with this QThread object has finished
752 execution (i.e. when it returns from \l{run()}). This function
753 will return true if the thread has finished. It also returns
754 true if the thread has not been started yet.
755 \li The \a deadline is reached. This function will return false if the
756 deadline is reached.
757 \endlist
758
759 A deadline timer set to \c QDeadlineTimer::Forever (the default) will never
760 time out: in this case, the function only returns when the thread returns
761 from \l{run()} or if the thread has not yet started.
762
763 This provides similar functionality to the POSIX \c
764 pthread_join() function.
765
766 \sa sleep(), terminate()
767*/
768
769/*!
770 \fn void QThread::setTerminationEnabled(bool enabled)
771
772 Enables or disables termination of the current thread based on the
773 \a enabled parameter. The thread must have been started by
774 QThread.
775
776 When \a enabled is false, termination is disabled. Future calls
777 to QThread::terminate() will return immediately without effect.
778 Instead, the termination is deferred until termination is enabled.
779
780 When \a enabled is true, termination is enabled. Future calls to
781 QThread::terminate() will terminate the thread normally. If
782 termination has been deferred (i.e. QThread::terminate() was
783 called with termination disabled), this function will terminate
784 the calling thread \e immediately. Note that this function will
785 not return in this case.
786
787 \sa terminate()
788*/
789
790/*!
791 \since 5.5
792 Returns the current event loop level for the thread.
793
794 \note This can only be called within the thread itself, i.e. when
795 it is the current thread.
796*/
797
798int QThread::loopLevel() const
799{
800 Q_D(const QThread);
801 return d->data->eventLoops.size();
802}
803
804#else // QT_CONFIG(thread)
805
806QThread::QThread(QObject *parent)
807 : QObject(*(new QThreadPrivate), parent)
808{
809 Q_D(QThread);
810 d->data->thread.storeRelaxed(this);
811}
812
813QThread::~QThread()
814{
815
816}
817
818void QThread::run()
819{
820
821}
822
823int QThread::exec()
824{
825 return 0;
826}
827
828void QThread::start(Priority priority)
829{
830 Q_D(QThread);
831 Q_UNUSED(priority);
832 d->running = true;
833}
834
835void QThread::terminate()
836{
837
838}
839
840void QThread::quit()
841{
842
843}
844
845void QThread::exit(int returnCode)
846{
847 Q_D(QThread);
848 d->data->quitNow = true;
849 for (int i = 0; i < d->data->eventLoops.size(); ++i) {
850 QEventLoop *eventLoop = d->data->eventLoops.at(i);
851 eventLoop->exit(returnCode);
852 }
853}
854
855bool QThread::wait(QDeadlineTimer deadline)
856{
857 Q_UNUSED(deadline);
858 return false;
859}
860
861bool QThread::event(QEvent *event)
862{
863 return QObject::event(event);
864}
865
866Qt::HANDLE QThread::currentThreadIdImpl() noexcept
867{
868 return Qt::HANDLE(currentThread());
869}
870
871QThread *QThread::currentThread()
872{
873 return QThreadData::current()->thread.loadAcquire();
874}
875
876int QThread::idealThreadCount() noexcept
877{
878 return 1;
879}
880
881void QThread::yieldCurrentThread()
882{
883
884}
885
886bool QThread::isFinished() const
887{
888 return false;
889}
890
891bool QThread::isRunning() const
892{
893 Q_D(const QThread);
894 return d->running;
895}
896
897// No threads: so we can just use static variables
898static QThreadData *data = nullptr;
899
900QThreadData *QThreadData::current(bool createIfNecessary)
901{
902 if (!data && createIfNecessary) {
903 data = new QThreadData;
904 data->thread = new QAdoptedThread(data);
905 data->threadId.storeRelaxed(Qt::HANDLE(data->thread.loadAcquire()));
906 data->deref();
907 data->isAdopted = true;
908 if (!QCoreApplicationPrivate::theMainThread.loadAcquire())
909 QCoreApplicationPrivate::theMainThread.storeRelease(data->thread.loadRelaxed());
910 }
911 return data;
912}
913
914void QThreadData::clearCurrentThreadData()
915{
916 delete data;
917 data = 0;
918}
919
920/*!
921 \internal
922 */
923QThread::QThread(QThreadPrivate &dd, QObject *parent)
924 : QObject(dd, parent)
925{
926 Q_D(QThread);
927 // fprintf(stderr, "QThreadData %p taken from private data for thread %p\n", d->data, this);
928 d->data->thread.storeRelaxed(this);
929}
930
931QThreadPrivate::QThreadPrivate(QThreadData *d) : data(d ? d : new QThreadData)
932{
933}
934
935QThreadPrivate::~QThreadPrivate()
936{
937 data->thread.storeRelease(nullptr); // prevent QThreadData from deleting the QThreadPrivate (again).
938 delete data;
939}
940
941void QThread::setStackSize(uint stackSize)
942{
943 Q_UNUSED(stackSize);
944}
945
946uint QThread::stackSize() const
947{
948 return 0;
949}
950
951#endif // QT_CONFIG(thread)
952
953/*!
954 \since 5.0
955
956 Returns a pointer to the event dispatcher object for the thread. If no event
957 dispatcher exists for the thread, this function returns \nullptr.
958*/
959QAbstractEventDispatcher *QThread::eventDispatcher() const
960{
961 Q_D(const QThread);
962 return d->data->eventDispatcher.loadRelaxed();
963}
964
965/*!
966 \since 5.0
967
968 Sets the event dispatcher for the thread to \a eventDispatcher. This is
969 only possible as long as there is no event dispatcher installed for the
970 thread yet. That is, before the thread has been started with start() or, in
971 case of the main thread, before QCoreApplication has been instantiated.
972 This method takes ownership of the object.
973*/
974void QThread::setEventDispatcher(QAbstractEventDispatcher *eventDispatcher)
975{
976 Q_D(QThread);
977 if (d->data->hasEventDispatcher()) {
978 qWarning("QThread::setEventDispatcher: An event dispatcher has already been created for this thread");
979 } else {
980 eventDispatcher->moveToThread(this);
981 if (eventDispatcher->thread() == this) // was the move successful?
982 d->data->eventDispatcher = eventDispatcher;
983 else
984 qWarning("QThread::setEventDispatcher: Could not move event dispatcher to target thread");
985 }
986}
987
988/*!
989 \fn bool QThread::wait(unsigned long time)
990 \overload
991*/
992
993#if QT_CONFIG(thread)
994
995/*!
996 \reimp
997*/
998bool QThread::event(QEvent *event)
999{
1000 if (event->type() == QEvent::Quit) {
1001 quit();
1002 return true;
1003 } else {
1004 return QObject::event(event);
1005 }
1006}
1007
1008/*!
1009 \since 5.2
1010 \threadsafe
1011
1012 Request the interruption of the thread.
1013 That request is advisory and it is up to code running on the thread to decide
1014 if and how it should act upon such request.
1015 This function does not stop any event loop running on the thread and
1016 does not terminate it in any way.
1017
1018 \sa isInterruptionRequested()
1019*/
1020
1021void QThread::requestInterruption()
1022{
1023 if (this == QCoreApplicationPrivate::theMainThread.loadAcquire()) {
1024 qWarning("QThread::requestInterruption has no effect on the main thread");
1025 return;
1026 }
1027 Q_D(QThread);
1028 // ### Qt 6: use std::atomic_flag, and document that
1029 // requestInterruption/isInterruptionRequested do not synchronize with each other
1030 QMutexLocker locker(&d->mutex);
1031 if (!d->running || d->finished || d->isInFinish)
1032 return;
1033 d->interruptionRequested.store(true, std::memory_order_relaxed);
1034}
1035
1036/*!
1037 \since 5.2
1038
1039 Return true if the task running on this thread should be stopped.
1040 An interruption can be requested by requestInterruption().
1041
1042 This function can be used to make long running tasks cleanly interruptible.
1043 Never checking or acting on the value returned by this function is safe,
1044 however it is advisable do so regularly in long running functions.
1045 Take care not to call it too often, to keep the overhead low.
1046
1047 \code
1048 void long_task() {
1049 forever {
1050 if ( QThread::currentThread()->isInterruptionRequested() ) {
1051 return;
1052 }
1053 }
1054 }
1055 \endcode
1056
1057 \note This can only be called within the thread itself, i.e. when
1058 it is the current thread.
1059
1060 \sa currentThread() requestInterruption()
1061*/
1062bool QThread::isInterruptionRequested() const
1063{
1064 Q_D(const QThread);
1065 // fast path: check that the flag is not set:
1066 if (!d->interruptionRequested.load(std::memory_order_relaxed))
1067 return false;
1068 // slow path: if the flag is set, take into account run status:
1069 QMutexLocker locker(&d->mutex);
1070 return d->running && !d->finished && !d->isInFinish;
1071}
1072
1073/*!
1074 \fn template <typename Function, typename... Args> QThread *QThread::create(Function &&f, Args &&... args)
1075 \since 5.10
1076
1077 Creates a new QThread object that will execute the function \a f with the
1078 arguments \a args.
1079
1080 The new thread is not started -- it must be started by an explicit call
1081 to start(). This allows you to connect to its signals, move QObjects
1082 to the thread, choose the new thread's priority and so on. The function
1083 \a f will be called in the new thread.
1084
1085 Returns the newly created QThread instance.
1086
1087 \note the caller acquires ownership of the returned QThread instance.
1088
1089 \warning do not call start() on the returned QThread instance more than once;
1090 doing so will result in undefined behavior.
1091
1092 \sa start()
1093*/
1094
1095#if QT_CONFIG(cxx11_future)
1096class QThreadCreateThread : public QThread
1097{
1098public:
1099 explicit QThreadCreateThread(std::future<void> &&future)
1100 : m_future(std::move(future))
1101 {
1102 }
1103
1104private:
1105 void run() override
1106 {
1107 m_future.get();
1108 }
1109
1110 std::future<void> m_future;
1111};
1112
1113QThread *QThread::createThreadImpl(std::future<void> &&future)
1114{
1115 return new QThreadCreateThread(std::move(future));
1116}
1117#endif // QT_CONFIG(cxx11_future)
1118
1119/*!
1120 \class QDaemonThread
1121 \since 5.5
1122 \brief The QDaemonThread provides a class to manage threads that outlive QCoreApplication
1123 \internal
1124
1125 Note: don't try to deliver events from the started() signal.
1126*/
1127QDaemonThread::QDaemonThread(QObject *parent)
1128 : QThread(parent)
1129{
1130 // QThread::started() is emitted from the thread we start
1131 connect(this, &QThread::started,
1132 [](){ QThreadData::current()->requiresCoreApplication = false; });
1133}
1134
1135QDaemonThread::~QDaemonThread()
1136{
1137}
1138
1139#endif // QT_CONFIG(thread)
1140
1141QT_END_NAMESPACE
1142
1143#include "moc_qthread.cpp"
1144