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