Qt
Internal/Contributor docs for the Qt SDK. Note: These are NOT official API docs; those are found at https://doc.qt.io/
Loading...
Searching...
No Matches
qthreadpool.cpp
Go to the documentation of this file.
1// Copyright (C) 2016 The Qt Company Ltd.
2// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
3// Qt-Security score:significant reason:default
4
5#include "qthreadpool.h"
9
10#include <QtCore/qpointer.h>
11
12#include <algorithm>
13#include <climits> // For INT_MAX
14#include <memory>
15
16using namespace std::chrono_literals;
17
18QT_BEGIN_NAMESPACE
19
20using namespace Qt::StringLiterals;
21
22namespace {
23struct QThreadGlobalPool
24{
25 QPointer<QThreadPool> theInstance;
26};
27QBasicMutex theMutex;
28}
29Q_GLOBAL_STATIC(QThreadGlobalPool, globalPool)
30
31#if !QT_CONFIG(thread)
32static void runRunnableInCurrentThread(QRunnable *runnable)
33{
34 Q_ASSERT(runnable);
35 const bool del = runnable->autoDelete();
36#ifndef QT_NO_EXCEPTIONS
37 try {
38#endif
39 runnable->run();
40#ifndef QT_NO_EXCEPTIONS
41 } catch (...) {
42 qWarning("Qt has caught an exception thrown from a runnable in a build "
43 "without thread support.");
44 }
45#endif
46 if (del)
47 delete runnable;
48}
49
50static void queueRunnable(QThreadPool *pool, QRunnable *runnable)
51{
52 QMetaObject::invokeMethod(pool, [runnable] {
53 runRunnableInCurrentThread(runnable);
54 }, Qt::QueuedConnection);
55}
56#endif
57
58/*
59 QThread wrapper, provides synchronization against a ThreadPool
60*/
73
74/*
75 QThreadPool private class.
76*/
78
79/*!
80 \internal
81*/
82QThreadPoolThread::QThreadPoolThread(QThreadPoolPrivate *manager)
83 :manager(manager), runnable(nullptr)
84{
85 setStackSize(manager->stackSize);
86}
87
88/*
89 \internal
90*/
92{
93 QMutexLocker locker(&manager->mutex);
94 for(;;) {
95 QRunnable *r = runnable;
96 runnable = nullptr;
97
98 do {
99 if (r) {
100 // If autoDelete() is false, r might already be deleted after run(), so check status now.
101 const bool del = r->autoDelete();
102
103 // run the task
104 locker.unlock();
105#ifndef QT_NO_EXCEPTIONS
106 try {
107#endif
108 r->run();
109#ifndef QT_NO_EXCEPTIONS
110 } catch (...) {
111 qWarning("Qt Concurrent has caught an exception thrown from a worker thread.\n"
112 "This is not supported, exceptions thrown in worker threads must be\n"
113 "caught before control returns to Qt Concurrent.");
115 throw;
116 }
117#endif
118
119 if (del)
120 delete r;
121 locker.relock();
122 }
123
124 // if too many threads are active, stop working in this one
126 break;
127
128 // all work is done, time to wait for more
129 if (manager->queue.isEmpty())
130 break;
131
132 QueuePage *page = manager->queue.constFirst();
133 r = page->pop();
134
135 if (page->isFinished()) {
136 manager->queue.removeFirst();
137 delete page;
138 }
139 } while (true);
140
141 // this thread is about to be deleted, do not wait or expire
142 if (!manager->allThreads.contains(this)) {
144 return;
145 }
146
147 // if too many threads are active, expire this thread
149 manager->expiredThreads.enqueue(this);
151 return;
152 }
153 manager->waitingThreads.enqueue(this);
155 // wait for work, exiting after the expiry timeout is reached
156 runnableReady.wait(locker.mutex(), QDeadlineTimer(manager->expiryTimeout));
157 // this thread is about to be deleted, do not work or expire
158 if (!manager->allThreads.contains(this)) {
159 Q_ASSERT(manager->queue.isEmpty());
160 return;
161 }
162 if (manager->waitingThreads.removeOne(this)) {
163 manager->expiredThreads.enqueue(this);
164 return;
165 }
167 }
168}
169
171{
172 if (--manager->activeThreads == 0)
173 manager->noActiveThreads.wakeAll();
174}
175
176
177/*
178 \internal
179*/
182
184{
185 if (!globalPool.exists())
186 return;
187
188 QThreadPool *globalThreadPool = []{
189 const QMutexLocker locker(&theMutex);
190 QThreadPool *p = globalPool->theInstance.get();
191 globalPool->theInstance = nullptr;
192 return p;
193 }();
194 if (globalThreadPool)
195 delete globalThreadPool;
196}
197
198bool QThreadPoolPrivate::tryStart(QRunnable *task)
199{
200 Q_ASSERT(task != nullptr);
201 if (allThreads.isEmpty()) {
202 // always create at least one thread
203 startThread(task);
204 return true;
205 }
206
207 // can't do anything if we're over the limit
209 return false;
210
211 if (!waitingThreads.isEmpty()) {
212 // recycle an available thread
213 enqueueTask(task);
214 waitingThreads.takeFirst()->runnableReady.wakeOne();
215 return true;
216 }
217
218 if (!expiredThreads.isEmpty()) {
219 // restart an expired thread
220 QThreadPoolThread *thread = expiredThreads.dequeue();
221 Q_ASSERT(thread->runnable == nullptr);
222
224
225 thread->runnable = task;
226
227 // Ensure that the thread has actually finished, otherwise the following
228 // start() has no effect.
229 thread->wait();
230 Q_ASSERT(thread->isFinished());
231 thread->start(threadPriority);
232 return true;
233 }
234
235 // start a new thread
236 startThread(task);
237 return true;
238}
239
240inline bool comparePriority(int priority, const QueuePage *p)
241{
242 return p->priority() < priority;
243}
244
245void QThreadPoolPrivate::enqueueTask(QRunnable *runnable, int priority)
246{
247 Q_ASSERT(runnable != nullptr);
248 for (QueuePage *page : std::as_const(queue)) {
249 if (page->priority() == priority && !page->isFull()) {
250 page->push(runnable);
251 return;
252 }
253 }
254 auto it = std::upper_bound(queue.constBegin(), queue.constEnd(), priority, comparePriority);
255 queue.insert(std::distance(queue.constBegin(), it), new QueuePage(runnable, priority));
256}
257
259{
260 return (allThreads.size()
261 - expiredThreads.size()
262 - waitingThreads.size()
263 + reservedThreads);
264}
265
267{
268 // try to push tasks on the queue to any available threads
269 while (!queue.isEmpty()) {
270 QueuePage *page = queue.constFirst();
271 if (!tryStart(page->first()))
272 break;
273
274 page->pop();
275
276 if (page->isFinished()) {
277 queue.removeFirst();
278 delete page;
279 }
280 }
281}
282
284{
285 const int activeThreadCount = this->activeThreadCount();
286 return activeThreadCount >= maxThreadCount() && (activeThreadCount - reservedThreads) >= 1;
287}
288
290{
291 const int activeThreadCount = this->activeThreadCount();
292 return activeThreadCount > maxThreadCount() && (activeThreadCount - reservedThreads) > 1;
293}
294
295/*!
296 \internal
297*/
298void QThreadPoolPrivate::startThread(QRunnable *runnable)
299{
300 Q_ASSERT(runnable != nullptr);
301 auto thread = std::make_unique<QThreadPoolThread>(this);
302 if (objectName.isEmpty())
303 objectName = u"Thread (pooled)"_s;
304 thread->setObjectName(objectName);
305 thread->setServiceLevel(serviceLevel);
306 Q_ASSERT(!allThreads.contains(thread.get())); // if this assert hits, we have an ABA problem (deleted threads don't get removed here)
307 allThreads.insert(thread.get());
309
310 thread->runnable = runnable;
311 thread.release()->start(threadPriority);
312}
313
314/*!
315 \internal
316
317 Helper function only to be called from waitForDone()
318
319 Deletes all current threads.
320*/
322{
323 // move the contents of the set out so that we can iterate without the lock
324 auto allThreadsCopy = std::exchange(allThreads, {});
325 expiredThreads.clear();
326 waitingThreads.clear();
327
328 mutex.unlock();
329
330 for (QThreadPoolThread *thread : std::as_const(allThreadsCopy)) {
331 if (thread->isRunning()) {
332 thread->runnableReady.wakeAll();
333 thread->wait();
334 }
335 delete thread;
336 }
337
338 mutex.lock();
339}
340
341/*!
342 \internal
343
344 Helper function only to be called from the public waitForDone()
345*/
346bool QThreadPoolPrivate::waitForDone(const QDeadlineTimer &timer)
347{
348 QMutexLocker locker(&mutex);
349 while (!(queue.isEmpty() && activeThreads == 0) && !timer.hasExpired())
350 noActiveThreads.wait(&mutex, timer);
351
352 if (!queue.isEmpty() || activeThreads)
353 return false;
354
355 reset();
356 // New jobs might have started during reset, but return anyway
357 // as the active thread and task count did reach 0 once, and
358 // race conditions are outside our scope.
359 return true;
360}
361
363{
364 QMutexLocker locker(&mutex);
365 while (!queue.isEmpty()) {
366 auto *page = queue.takeLast();
367 while (!page->isFinished()) {
368 QRunnable *r = page->pop();
369 if (r && r->autoDelete()) {
370 locker.unlock();
371 delete r;
372 locker.relock();
373 }
374 }
375 delete page;
376 }
377}
378
379/*!
380 \since 5.9
381
382 Attempts to remove the specified \a runnable from the queue if it is not yet started.
383 If the runnable had not been started, returns \c true, and ownership of \a runnable
384 is transferred to the caller (even when \c{runnable->autoDelete() == true}).
385 Otherwise returns \c false.
386
387 \note If \c{runnable->autoDelete() == true}, this function may remove the wrong
388 runnable. This is known as the \l{https://en.wikipedia.org/wiki/ABA_problem}{ABA problem}:
389 the original \a runnable may already have executed and has since been deleted.
390 The memory is re-used for another runnable, which then gets removed instead of
391 the intended one. For this reason, we recommend calling this function only for
392 runnables that are not auto-deleting.
393
394 \sa start(), QRunnable::autoDelete()
395*/
396bool QThreadPool::tryTake(QRunnable *runnable)
397{
398 Q_D(QThreadPool);
399
400 if (runnable == nullptr)
401 return false;
402
403 QMutexLocker locker(&d->mutex);
404 for (QueuePage *page : std::as_const(d->queue)) {
405 if (page->tryTake(runnable)) {
406 if (page->isFinished()) {
407 d->queue.removeOne(page);
408 delete page;
409 }
410 return true;
411 }
412 }
413
414 return false;
415}
416
417 /*!
418 \internal
419 Searches for \a runnable in the queue, removes it from the queue and
420 runs it if found. This function does not return until the runnable
421 has completed.
422 */
423void QThreadPoolPrivate::stealAndRunRunnable(QRunnable *runnable)
424{
425 Q_Q(QThreadPool);
426 if (!q->tryTake(runnable))
427 return;
428 // If autoDelete() is false, runnable might already be deleted after run(), so check status now.
429 const bool del = runnable->autoDelete();
430
431 runnable->run();
432
433 if (del)
434 delete runnable;
435}
436
437/*!
438 \class QThreadPool
439 \inmodule QtCore
440 \brief The QThreadPool class manages a collection of QThreads.
441 \since 4.4
442 \threadsafe
443
444 \ingroup thread
445
446 QThreadPool manages and recycles individual QThread objects to help reduce
447 thread creation costs in programs that use threads. Each Qt application
448 has one global QThreadPool object, which can be accessed by calling
449 globalInstance().
450
451 To use one of the QThreadPool threads, subclass QRunnable and implement
452 the run() virtual function. Then create an object of that class and pass
453 it to QThreadPool::start().
454
455 \snippet code/src_corelib_concurrent_qthreadpool.cpp 0
456
457 QThreadPool deletes the QRunnable automatically by default. Use
458 QRunnable::setAutoDelete() to change the auto-deletion flag.
459
460 QThreadPool supports executing the same QRunnable more than once
461 by calling tryStart(this) from within QRunnable::run().
462 If autoDelete is enabled the QRunnable will be deleted when
463 the last thread exits the run function. Calling start()
464 multiple times with the same QRunnable when autoDelete is enabled
465 creates a race condition and is not recommended.
466
467 Threads that are unused for a certain amount of time will expire. The
468 default expiry timeout is 30000 milliseconds (30 seconds). This can be
469 changed using setExpiryTimeout(). Setting a negative expiry timeout
470 disables the expiry mechanism.
471
472 Call maxThreadCount() to query the maximum number of threads to be used.
473 If needed, you can change the limit with setMaxThreadCount(). The default
474 maxThreadCount() is QThread::idealThreadCount(). The activeThreadCount()
475 function returns the number of threads currently doing work.
476
477 The reserveThread() function reserves a thread for external
478 use. Use releaseThread() when your are done with the thread, so
479 that it may be reused. Essentially, these functions temporarily
480 increase or reduce the active thread count and are useful when
481 implementing time-consuming operations that are not visible to the
482 QThreadPool.
483
484 Note that QThreadPool is a low-level class for managing threads, see
485 the Qt Concurrent module for higher level alternatives.
486
487 \sa QRunnable
488*/
489
490/*!
491 Constructs a thread pool with the given \a parent.
492*/
493QThreadPool::QThreadPool(QObject *parent)
494 : QObject(*new QThreadPoolPrivate, parent)
495{
496 Q_D(QThreadPool);
497 connect(this, &QObject::objectNameChanged, this, [d](const QString &newName) {
498 // We keep a copy of the name under our own lock, so we can access it thread-safely.
499 QMutexLocker locker(&d->mutex);
500 d->objectName = newName;
501 });
502}
503
504/*!
505 Destroys the QThreadPool.
506 This function will block until all runnables have been completed.
507*/
508QThreadPool::~QThreadPool()
509{
510 Q_D(QThreadPool);
511 waitForDone();
512 Q_ASSERT(d->queue.isEmpty());
513 Q_ASSERT(d->allThreads.isEmpty());
514}
515
516/*!
517 Returns the global QThreadPool instance.
518*/
519QThreadPool *QThreadPool::globalInstance()
520{
521 if (!globalPool.exists() && QCoreApplication::closingDown())
522 return nullptr; // don't create
523
524 QPointer<QThreadPool> &theInstance = globalPool->theInstance;
525 const QMutexLocker locker(&theMutex);
526 if (!theInstance)
527 theInstance = new QThreadPool();
528 return theInstance;
529}
530
531/*!
532 Reserves a thread and uses it to run \a runnable, unless this thread will
533 make the current thread count exceed maxThreadCount(). In that case,
534 \a runnable is added to a run queue instead. The \a priority argument can
535 be used to control the run queue's order of execution.
536
537 Note that the thread pool takes ownership of the \a runnable if
538 \l{QRunnable::autoDelete()}{runnable->autoDelete()} returns \c true,
539 and the \a runnable will be deleted automatically by the thread
540 pool after the \l{QRunnable::run()}{runnable->run()} returns. If
541 \l{QRunnable::autoDelete()}{runnable->autoDelete()} returns \c false,
542 ownership of \a runnable remains with the caller. Note that
543 changing the auto-deletion on \a runnable after calling this
544 functions results in undefined behavior.
545*/
546void QThreadPool::start(QRunnable *runnable, int priority)
547{
548 if (!runnable)
549 return;
550
551#if !QT_CONFIG(thread)
552 Q_UNUSED(priority);
553 queueRunnable(this, runnable);
554 return;
555#else
556 Q_D(QThreadPool);
557 QMutexLocker locker(&d->mutex);
558
559 if (!d->tryStart(runnable))
560 d->enqueueTask(runnable, priority);
561#endif
562}
563
564/*!
565 \fn template<typename Callable, QRunnable::if_callable<Callable>> void QThreadPool::start(Callable &&callableToRun, int priority)
566 \overload
567 \since 5.15
568
569 Reserves a thread and uses it to run \a callableToRun, unless this thread will
570 make the current thread count exceed maxThreadCount(). In that case,
571 \a callableToRun is added to a run queue instead. The \a priority argument can
572 be used to control the run queue's order of execution.
573
574 \note In Qt version prior to 6.6, this function took std::function<void()>,
575 and therefore couldn't handle move-only callables.
576
577 \constraints \c Callable
578 is a function or function object which can be called with zero arguments.
579*/
580
581/*!
582 Attempts to reserve a thread to run \a runnable.
583
584 If no threads are available at the time of calling, then this function
585 does nothing and returns \c false. Otherwise, \a runnable is run immediately
586 using one available thread and this function returns \c true.
587
588 Note that on success the thread pool takes ownership of the \a runnable if
589 \l{QRunnable::autoDelete()}{runnable->autoDelete()} returns \c true,
590 and the \a runnable will be deleted automatically by the thread
591 pool after the \l{QRunnable::run()}{runnable->run()} returns. If
592 \l{QRunnable::autoDelete()}{runnable->autoDelete()} returns \c false,
593 ownership of \a runnable remains with the caller. Note that
594 changing the auto-deletion on \a runnable after calling this
595 function results in undefined behavior.
596*/
597bool QThreadPool::tryStart(QRunnable *runnable)
598{
599 if (!runnable)
600 return false;
601
602#if !QT_CONFIG(thread)
603 queueRunnable(this, runnable);
604 return true;
605#else
606 Q_D(QThreadPool);
607 QMutexLocker locker(&d->mutex);
608 if (d->tryStart(runnable))
609 return true;
610
611 return false;
612#endif
613}
614
615/*!
616 \fn template<typename Callable, QRunnable::if_callable<Callable>> bool QThreadPool::tryStart(Callable &&callableToRun)
617 \overload
618 \since 5.15
619 Attempts to reserve a thread to run \a callableToRun.
620
621 If no threads are available at the time of calling, then this function
622 does nothing and returns \c false. Otherwise, \a callableToRun is run immediately
623 using one available thread and this function returns \c true.
624
625 \note In Qt version prior to 6.6, this function took std::function<void()>,
626 and therefore couldn't handle move-only callables.
627
628 \constraints \c Callable
629 is a function or function object which can be called with zero arguments.
630*/
631
632/*! \property QThreadPool::expiryTimeout
633 \brief the thread expiry timeout value in milliseconds.
634
635 Threads that are unused for \e expiryTimeout milliseconds are considered
636 to have expired and will exit. Such threads will be restarted as needed.
637 The default \a expiryTimeout is 30000 milliseconds (30 seconds). If
638 \a expiryTimeout is negative, newly created threads will not expire, e.g.,
639 they will not exit until the thread pool is destroyed.
640
641 Note that setting \a expiryTimeout has no effect on already running
642 threads. Only newly created threads will use the new \a expiryTimeout.
643 We recommend setting the \a expiryTimeout immediately after creating the
644 thread pool, but before calling start().
645*/
646
647int QThreadPool::expiryTimeout() const
648{
649 using namespace std::chrono;
650 Q_D(const QThreadPool);
651 QMutexLocker locker(&d->mutex);
652 if (d->expiryTimeout == decltype(d->expiryTimeout)::max())
653 return -1;
654 return duration_cast<milliseconds>(d->expiryTimeout).count();
655}
656
657void QThreadPool::setExpiryTimeout(int expiryTimeout)
658{
659 Q_D(QThreadPool);
660 QMutexLocker locker(&d->mutex);
661 if (expiryTimeout < 0)
662 d->expiryTimeout = decltype(d->expiryTimeout)::max();
663 else
664 d->expiryTimeout = expiryTimeout * 1ms;
665}
666
667/*! \property QThreadPool::maxThreadCount
668
669 \brief the maximum number of threads used by the thread pool. This property
670 will default to the value of QThread::idealThreadCount() at the moment the
671 QThreadPool object is created.
672
673 \note The thread pool will always use at least 1 thread, even if
674 \a maxThreadCount limit is zero or negative.
675
676 The default \a maxThreadCount is QThread::idealThreadCount().
677*/
678
679int QThreadPool::maxThreadCount() const
680{
681 Q_D(const QThreadPool);
682 QMutexLocker locker(&d->mutex);
683 return d->requestedMaxThreadCount;
684}
685
686void QThreadPool::setMaxThreadCount(int maxThreadCount)
687{
688 Q_D(QThreadPool);
689 QMutexLocker locker(&d->mutex);
690
691 if (maxThreadCount == d->requestedMaxThreadCount)
692 return;
693
694 d->requestedMaxThreadCount = maxThreadCount;
695 d->tryToStartMoreThreads();
696}
697
698/*! \property QThreadPool::activeThreadCount
699
700 \brief the number of active threads in the thread pool.
701
702 \note It is possible for this function to return a value that is greater
703 than maxThreadCount(). See reserveThread() for more details.
704
705 \sa reserveThread(), releaseThread()
706*/
707
708int QThreadPool::activeThreadCount() const
709{
710 Q_D(const QThreadPool);
711 QMutexLocker locker(&d->mutex);
712 return d->activeThreadCount();
713}
714
715/*!
716 Reserves one thread, disregarding activeThreadCount() and maxThreadCount().
717
718 Once you are done with the thread, call releaseThread() to allow it to be
719 reused.
720
721 \note Even if reserving maxThreadCount() threads or more, the thread pool
722 will still allow a minimum of one thread.
723
724 \note This function will increase the reported number of active threads.
725 This means that by using this function, it is possible for
726 activeThreadCount() to return a value greater than maxThreadCount() .
727
728 \sa releaseThread()
729 */
730void QThreadPool::reserveThread()
731{
732 Q_D(QThreadPool);
733 QMutexLocker locker(&d->mutex);
734 ++d->reservedThreads;
735}
736
737/*! \property QThreadPool::stackSize
738 \brief the stack size for the thread pool worker threads.
739
740 The value of the property is only used when the thread pool creates
741 new threads. Changing it has no effect for already created
742 or running threads.
743
744 The default value is 0, which makes QThread use the operating
745 system default stack size.
746
747 \since 5.10
748*/
749void QThreadPool::setStackSize(uint stackSize)
750{
751 Q_D(QThreadPool);
752 QMutexLocker locker(&d->mutex);
753 d->stackSize = stackSize;
754}
755
756uint QThreadPool::stackSize() const
757{
758 Q_D(const QThreadPool);
759 QMutexLocker locker(&d->mutex);
760 return d->stackSize;
761}
762
763/*! \property QThreadPool::threadPriority
764 \brief the thread priority for new worker threads.
765
766 The value of the property is only used when the thread pool starts
767 new threads. Changing it has no effect for already running threads.
768
769 The default value is QThread::InheritPriority, which makes QThread
770 use the same priority as the one the QThreadPool object lives in.
771
772 \sa QThread::Priority
773
774 \since 6.2
775*/
776
777void QThreadPool::setThreadPriority(QThread::Priority priority)
778{
779 Q_D(QThreadPool);
780 QMutexLocker locker(&d->mutex);
781 d->threadPriority = priority;
782}
783
784QThread::Priority QThreadPool::threadPriority() const
785{
786 Q_D(const QThreadPool);
787 QMutexLocker locker(&d->mutex);
788 return d->threadPriority;
789}
790
791/*!
792 Releases a thread previously reserved by a call to reserveThread().
793
794 \note Calling this function without previously reserving a thread
795 temporarily increases maxThreadCount(). This is useful when a
796 thread goes to sleep waiting for more work, allowing other threads
797 to continue. Be sure to call reserveThread() when done waiting, so
798 that the thread pool can correctly maintain the
799 activeThreadCount().
800
801 \sa reserveThread()
802*/
803void QThreadPool::releaseThread()
804{
805 Q_D(QThreadPool);
806 QMutexLocker locker(&d->mutex);
807 --d->reservedThreads;
808 d->tryToStartMoreThreads();
809}
810
811/*!
812 \since 6.9
813
814 Sets the Quality of Service level of thread objects created after the call
815 to this setter to \a serviceLevel.
816
817 Support is not available on every platform. Consult
818 QThread::setServiceLevel() for details.
819
820 \sa serviceLevel(), QThread::serviceLevel()
821*/
822void QThreadPool::setServiceLevel(QThread::QualityOfService serviceLevel)
823{
824 Q_D(QThreadPool);
825 QMutexLocker locker(&d->mutex);
826 d->serviceLevel = serviceLevel;
827}
828
829/*!
830 \since 6.9
831
832 Returns the current Quality of Service level of the thread.
833
834 \sa setServiceLevel(), QThread::serviceLevel()
835*/
836QThread::QualityOfService QThreadPool::serviceLevel() const
837{
838 Q_D(const QThreadPool);
839 QMutexLocker locker(&d->mutex);
840 return d->serviceLevel;
841}
842
843/*!
844 Releases a thread previously reserved with reserveThread() and uses it
845 to run \a runnable.
846
847 Note that the thread pool takes ownership of the \a runnable if
848 \l{QRunnable::autoDelete()}{runnable->autoDelete()} returns \c true,
849 and the \a runnable will be deleted automatically by the thread
850 pool after the \l{QRunnable::run()}{runnable->run()} returns. If
851 \l{QRunnable::autoDelete()}{runnable->autoDelete()} returns \c false,
852 ownership of \a runnable remains with the caller. Note that
853 changing the auto-deletion on \a runnable after calling this
854 functions results in undefined behavior.
855
856 \note Calling this when no threads are reserved results in
857 undefined behavior.
858
859 \since 6.3
860 \sa reserveThread(), start()
861*/
862void QThreadPool::startOnReservedThread(QRunnable *runnable)
863{
864 if (!runnable)
865 return releaseThread();
866
867#if !QT_CONFIG(thread)
868 queueRunnable(this, runnable);
869 return;
870#else
871 Q_D(QThreadPool);
872 QMutexLocker locker(&d->mutex);
873 Q_ASSERT(d->reservedThreads > 0);
874 --d->reservedThreads;
875
876 if (!d->tryStart(runnable)) {
877 // This can only happen if we reserved max threads,
878 // and something took the one minimum thread.
879 d->enqueueTask(runnable, INT_MAX);
880 }
881#endif
882}
883
884/*!
885 \fn template<typename Callable, QRunnable::if_callable<Callable>> void QThreadPool::startOnReservedThread(Callable &&callableToRun)
886 \overload
887 \since 6.3
888
889 Releases a thread previously reserved with reserveThread() and uses it
890 to run \a callableToRun.
891
892 \note In Qt version prior to 6.6, this function took std::function<void()>,
893 and therefore couldn't handle move-only callables.
894
895 \constraints \c Callable
896 is a function or function object which can be called with zero arguments.
897*/
898
899/*!
900 \fn bool QThreadPool::waitForDone(int msecs)
901 Waits up to \a msecs milliseconds for all threads to exit and removes all
902 threads from the thread pool. Returns \c true if all threads were removed;
903 otherwise it returns \c false. If \a msecs is -1, this function waits for
904 the last thread to exit.
905*/
906
907/*!
908 \since 6.8
909
910 Waits until \a deadline expires for all threads to exit and removes all
911 threads from the thread pool. Returns \c true if all threads were removed;
912 otherwise it returns \c false.
913*/
914bool QThreadPool::waitForDone(QDeadlineTimer deadline)
915{
916 Q_D(QThreadPool);
917 return d->waitForDone(deadline);
918}
919
920/*!
921 \since 5.2
922
923 Removes the runnables that are not yet started from the queue.
924 The runnables for which \l{QRunnable::autoDelete()}{runnable->autoDelete()}
925 returns \c true are deleted.
926
927 \sa start()
928*/
929void QThreadPool::clear()
930{
931 Q_D(QThreadPool);
932 d->clear();
933}
934
935/*!
936 \since 6.0
937
938 Returns \c true if \a thread is a thread managed by this thread pool.
939*/
940bool QThreadPool::contains(const QThread *thread) const
941{
942 Q_D(const QThreadPool);
943 const QThreadPoolThread *poolThread = qobject_cast<const QThreadPoolThread *>(thread);
944 if (!poolThread)
945 return false;
946 QMutexLocker locker(&d->mutex);
947 return d->allThreads.contains(const_cast<QThreadPoolThread *>(poolThread));
948}
949
950QT_END_NAMESPACE
951
952#include "moc_qthreadpool.cpp"
953#include "qthreadpool.moc"
bool areAllThreadsActive() const
bool tryStart(QRunnable *task)
void enqueueTask(QRunnable *task, int priority=0)
static void destroyGlobalThreadPool()
int activeThreadCount() const
int maxThreadCount() const
void startThread(QRunnable *runnable=nullptr)
void stealAndRunRunnable(QRunnable *runnable)
bool waitForDone(const QDeadlineTimer &timer)
bool tooManyThreadsActive() const
void run() override
QThreadPoolPrivate * manager
void registerThreadInactive()
QRunnable * runnable
QWaitCondition runnableReady
bool comparePriority(int priority, const QueuePage *p)
QThreadPoolPrivate::QueuePage QueuePage