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