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 Class Reference

\inmodule QtCore More...

#include <qthreadpool.h>

+ Inheritance diagram for QThreadPool:
+ Collaboration diagram for QThreadPool:

Public Member Functions

 QThreadPool (QObject *parent=nullptr)
 Constructs a thread pool with the given parent.
 
 ~QThreadPool ()
 Destroys the QThreadPool.
 
void start (QRunnable *runnable, int priority=0)
 Reserves a thread and uses it to run runnable, unless this thread will make the current thread count exceed maxThreadCount().
 
bool tryStart (QRunnable *runnable)
 Attempts to reserve a thread to run runnable.
 
void startOnReservedThread (QRunnable *runnable)
 Releases a thread previously reserved with reserveThread() and uses it to run runnable.
 
template<typename Callable , QRunnable::if_callable< Callable > = true>
void start (Callable &&functionToRun, int priority=0)
 
template<typename Callable , QRunnable::if_callable< Callable > = true>
bool tryStart (Callable &&functionToRun)
 
template<typename Callable , QRunnable::if_callable< Callable > = true>
void startOnReservedThread (Callable &&functionToRun)
 
int expiryTimeout () const
 
void setExpiryTimeout (int expiryTimeout)
 
int maxThreadCount () const
 
void setMaxThreadCount (int maxThreadCount)
 
int activeThreadCount () const
 
void setStackSize (uint stackSize)
 
uint stackSize () const
 
void setThreadPriority (QThread::Priority priority)
 
QThread::Priority threadPriority () const
 
void reserveThread ()
 Reserves one thread, disregarding activeThreadCount() and maxThreadCount().
 
void releaseThread ()
 Releases a thread previously reserved by a call to reserveThread().
 
bool waitForDone (int msecs)
 Waits up to msecs milliseconds for all threads to exit and removes all threads from the thread pool.
 
bool waitForDone (QDeadlineTimer deadline=QDeadlineTimer::Forever)
 
void clear ()
 
bool contains (const QThread *thread) const
 
bool tryTake (QRunnable *runnable)
 
- Public Member Functions inherited from QObject
Q_INVOKABLE QObject (QObject *parent=nullptr)
 Constructs an object with parent object parent.
 
virtual ~QObject ()
 Destroys the object, deleting all its child objects.
 
virtual bool event (QEvent *event)
 This virtual function receives events to an object and should return true if the event e was recognized and processed.
 
virtual bool eventFilter (QObject *watched, QEvent *event)
 Filters events if this object has been installed as an event filter for the watched object.
 
QString objectName () const
 
Q_WEAK_OVERLOAD void setObjectName (const QString &name)
 Sets the object's name to name.
 
void setObjectName (QAnyStringView name)
 This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.
 
QBindable< QStringbindableObjectName ()
 
bool isWidgetType () const
 Returns true if the object is a widget; otherwise returns false.
 
bool isWindowType () const
 Returns true if the object is a window; otherwise returns false.
 
bool isQuickItemType () const
 Returns true if the object is a QQuickItem; otherwise returns false.
 
bool signalsBlocked () const noexcept
 Returns true if signals are blocked; otherwise returns false.
 
bool blockSignals (bool b) noexcept
 If block is true, signals emitted by this object are blocked (i.e., emitting a signal will not invoke anything connected to it).
 
QThreadthread () const
 Returns the thread in which the object lives.
 
bool moveToThread (QThread *thread QT6_DECL_NEW_OVERLOAD_TAIL)
 Changes the thread affinity for this object and its children and returns true on success.
 
int startTimer (int interval, Qt::TimerType timerType=Qt::CoarseTimer)
 This is an overloaded function that will start a timer of type timerType and a timeout of interval milliseconds.
 
int startTimer (std::chrono::nanoseconds time, Qt::TimerType timerType=Qt::CoarseTimer)
 
void killTimer (int id)
 Kills the timer with timer identifier, id.
 
void killTimer (Qt::TimerId id)
 
template<typename T >
findChild (QAnyStringView aName, Qt::FindChildOptions options=Qt::FindChildrenRecursively) const
 Returns the child of this object that can be cast into type T and that is called name, or \nullptr if there is no such object.
 
template<typename T >
QList< T > findChildren (QAnyStringView aName, Qt::FindChildOptions options=Qt::FindChildrenRecursively) const
 Returns all children of this object with the given name that can be cast to type T, or an empty list if there are no such objects.
 
template<typename T >
findChild (Qt::FindChildOptions options=Qt::FindChildrenRecursively) const
 This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.
 
template<typename T >
QList< T > findChildren (Qt::FindChildOptions options=Qt::FindChildrenRecursively) const
 This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.
 
const QObjectListchildren () const
 Returns a list of child objects.
 
void setParent (QObject *parent)
 Makes the object a child of parent.
 
void installEventFilter (QObject *filterObj)
 Installs an event filter filterObj on this object.
 
void removeEventFilter (QObject *obj)
 Removes an event filter object obj from this object.
 
QMetaObject::Connection connect (const QObject *sender, const char *signal, const char *member, Qt::ConnectionType type=Qt::AutoConnection) const
 
bool disconnect (const char *signal=nullptr, const QObject *receiver=nullptr, const char *member=nullptr) const
 
bool disconnect (const QObject *receiver, const char *member=nullptr) const
 
void dumpObjectTree () const
 Dumps a tree of children to the debug output.
 
void dumpObjectInfo () const
 Dumps information about signal connections, etc.
 
bool setProperty (const char *name, const QVariant &value)
 Sets the value of the object's name property to value.
 
bool setProperty (const char *name, QVariant &&value)
 
QVariant property (const char *name) const
 Returns the value of the object's name property.
 
QList< QByteArraydynamicPropertyNames () const
 
QBindingStoragebindingStorage ()
 
const QBindingStoragebindingStorage () const
 
QObjectparent () const
 Returns a pointer to the parent object.
 
bool inherits (const char *classname) const
 Returns true if this object is an instance of a class that inherits className or a QObject subclass that inherits className; otherwise returns false.
 

Static Public Member Functions

static QThreadPoolglobalInstance ()
 Returns the global QThreadPool instance.
 
- Static Public Member Functions inherited from QObject
static QMetaObject::Connection connect (const QObject *sender, const char *signal, const QObject *receiver, const char *member, Qt::ConnectionType=Qt::AutoConnection)
 \threadsafe
 
static QMetaObject::Connection connect (const QObject *sender, const QMetaMethod &signal, const QObject *receiver, const QMetaMethod &method, Qt::ConnectionType type=Qt::AutoConnection)
 
template<typename Func1 , typename Func2 >
static QMetaObject::Connection connect (const typename QtPrivate::FunctionPointer< Func1 >::Object *sender, Func1 signal, const typename QtPrivate::ContextTypeForFunctor< Func2 >::ContextType *context, Func2 &&slot, Qt::ConnectionType type=Qt::AutoConnection)
 
template<typename Func1 , typename Func2 >
static QMetaObject::Connection connect (const typename QtPrivate::FunctionPointer< Func1 >::Object *sender, Func1 signal, Func2 &&slot)
 
static bool disconnect (const QObject *sender, const char *signal, const QObject *receiver, const char *member)
 \threadsafe
 
static bool disconnect (const QObject *sender, const QMetaMethod &signal, const QObject *receiver, const QMetaMethod &member)
 
static bool disconnect (const QMetaObject::Connection &)
 Disconnect a connection.
 
template<typename Func1 , typename Func2 >
static bool disconnect (const typename QtPrivate::FunctionPointer< Func1 >::Object *sender, Func1 signal, const typename QtPrivate::FunctionPointer< Func2 >::Object *receiver, Func2 slot)
 
template<typename Func1 >
static bool disconnect (const typename QtPrivate::FunctionPointer< Func1 >::Object *sender, Func1 signal, const QObject *receiver, void **zero)
 

Properties

int expiryTimeout
 the thread expiry timeout value in milliseconds.
 
int maxThreadCount
 the maximum number of threads used by the thread pool.
 
int activeThreadCount
 the number of active threads in the thread pool.
 
uint stackSize
 the stack size for the thread pool worker threads.
 
QThread::Priority threadPriority
 the thread priority for new worker threads.
 
- Properties inherited from QObject
QString objectName
 the name of this object
 

Friends

class QFutureInterfaceBase
 

Additional Inherited Members

- Public Slots inherited from QObject
void deleteLater ()
 \threadsafe
 
- Signals inherited from QObject
void destroyed (QObject *=nullptr)
 This signal is emitted immediately before the object obj is destroyed, after any instances of QPointer have been notified, and cannot be blocked.
 
void objectNameChanged (const QString &objectName, QPrivateSignal)
 This signal is emitted after the object's name has been changed.
 
- Protected Member Functions inherited from QObject
QObjectsender () const
 Returns a pointer to the object that sent the signal, if called in a slot activated by a signal; otherwise it returns \nullptr.
 
int senderSignalIndex () const
 
int receivers (const char *signal) const
 Returns the number of receivers connected to the signal.
 
bool isSignalConnected (const QMetaMethod &signal) const
 
virtual void timerEvent (QTimerEvent *event)
 This event handler can be reimplemented in a subclass to receive timer events for the object.
 
virtual void childEvent (QChildEvent *event)
 This event handler can be reimplemented in a subclass to receive child events.
 
virtual void customEvent (QEvent *event)
 This event handler can be reimplemented in a subclass to receive custom events.
 
virtual void connectNotify (const QMetaMethod &signal)
 
virtual void disconnectNotify (const QMetaMethod &signal)
 
 QObject (QObjectPrivate &dd, QObject *parent=nullptr)
 
- Protected Attributes inherited from QObject
QScopedPointer< QObjectDatad_ptr
 

Detailed Description

\inmodule QtCore

The QThreadPool class manages a collection of QThreads.

Since
4.4 \threadsafe

QThreadPool manages and recycles individual QThread objects to help reduce thread creation costs in programs that use threads. Each Qt application has one global QThreadPool object, which can be accessed by calling globalInstance().

To use one of the QThreadPool threads, subclass QRunnable and implement the run() virtual function. Then create an object of that class and pass it to QThreadPool::start().

class HelloWorldTask : public QRunnable
{
void run() override
{
qDebug() << "Hello world from thread" << QThread::currentThread();
}
};
// QThreadPool takes ownership and deletes 'hello' automatically
void run() override
Implement this pure virtual function in your subclass.
\inmodule QtCore
Definition qrunnable.h:18
void start(QRunnable *runnable, int priority=0)
Reserves a thread and uses it to run runnable, unless this thread will make the current thread count ...
static QThreadPool * globalInstance()
Returns the global QThreadPool instance.
static QThread * currentThread()
Definition qthread.cpp:1069

QThreadPool deletes the QRunnable automatically by default. Use QRunnable::setAutoDelete() to change the auto-deletion flag.

QThreadPool supports executing the same QRunnable more than once by calling tryStart(this) from within QRunnable::run(). If autoDelete is enabled the QRunnable will be deleted when the last thread exits the run function. Calling start() multiple times with the same QRunnable when autoDelete is enabled creates a race condition and is not recommended.

Threads that are unused for a certain amount of time will expire. The default expiry timeout is 30000 milliseconds (30 seconds). This can be changed using setExpiryTimeout(). Setting a negative expiry timeout disables the expiry mechanism.

Call maxThreadCount() to query the maximum number of threads to be used. If needed, you can change the limit with setMaxThreadCount(). The default maxThreadCount() is QThread::idealThreadCount(). The activeThreadCount() function returns the number of threads currently doing work.

The reserveThread() function reserves a thread for external use. Use releaseThread() when your are done with the thread, so that it may be reused. Essentially, these functions temporarily increase or reduce the active thread count and are useful when implementing time-consuming operations that are not visible to the QThreadPool.

Note that QThreadPool is a low-level class for managing threads, see the Qt Concurrent module for higher level alternatives.

See also
QRunnable

Definition at line 21 of file qthreadpool.h.

Constructor & Destructor Documentation

◆ QThreadPool()

QThreadPool::QThreadPool ( QObject * parent = nullptr)

Constructs a thread pool with the given parent.

Definition at line 439 of file qthreadpool.cpp.

◆ ~QThreadPool()

QThreadPool::~QThreadPool ( )

Destroys the QThreadPool.

This function will block until all runnables have been completed.

Definition at line 454 of file qthreadpool.cpp.

Member Function Documentation

◆ activeThreadCount()

int QThreadPool::activeThreadCount ( ) const

Definition at line 662 of file qthreadpool.cpp.

◆ clear()

void QThreadPool::clear ( )
Since
5.2

Removes the runnables that are not yet started from the queue. The runnables for which \l{QRunnable::autoDelete()}{runnable->autoDelete()} returns true are deleted.

See also
start()

Definition at line 846 of file qthreadpool.cpp.

◆ contains()

bool QThreadPool::contains ( const QThread * thread) const
Since
6.0

Returns true if thread is a thread managed by this thread pool.

Definition at line 857 of file qthreadpool.cpp.

◆ expiryTimeout()

int QThreadPool::expiryTimeout ( ) const

Definition at line 601 of file qthreadpool.cpp.

◆ globalInstance()

QThreadPool * QThreadPool::globalInstance ( )
static

Returns the global QThreadPool instance.

Definition at line 465 of file qthreadpool.cpp.

◆ maxThreadCount()

int QThreadPool::maxThreadCount ( ) const

Definition at line 633 of file qthreadpool.cpp.

◆ releaseThread()

void QThreadPool::releaseThread ( )

Releases a thread previously reserved by a call to reserveThread().

Note
Calling this function without previously reserving a thread temporarily increases maxThreadCount(). This is useful when a thread goes to sleep waiting for more work, allowing other threads to continue. Be sure to call reserveThread() when done waiting, so that the thread pool can correctly maintain the activeThreadCount().
See also
reserveThread()

Definition at line 757 of file qthreadpool.cpp.

◆ reserveThread()

void QThreadPool::reserveThread ( )

Reserves one thread, disregarding activeThreadCount() and maxThreadCount().

Once you are done with the thread, call releaseThread() to allow it to be reused.

Note
Even if reserving maxThreadCount() threads or more, the thread pool will still allow a minimum of one thread.
This function will increase the reported number of active threads. This means that by using this function, it is possible for activeThreadCount() to return a value greater than maxThreadCount() .
See also
releaseThread()

Definition at line 684 of file qthreadpool.cpp.

◆ setExpiryTimeout()

void QThreadPool::setExpiryTimeout ( int expiryTimeout)

Definition at line 611 of file qthreadpool.cpp.

◆ setMaxThreadCount()

void QThreadPool::setMaxThreadCount ( int maxThreadCount)

Definition at line 640 of file qthreadpool.cpp.

◆ setStackSize()

void QThreadPool::setStackSize ( uint stackSize)

Definition at line 703 of file qthreadpool.cpp.

◆ setThreadPriority()

void QThreadPool::setThreadPriority ( QThread::Priority priority)

Definition at line 731 of file qthreadpool.cpp.

◆ stackSize()

uint QThreadPool::stackSize ( ) const

Definition at line 710 of file qthreadpool.cpp.

◆ start() [1/2]

template<typename Callable , QRunnable::if_callable< Callable > >
void QThreadPool::start ( Callable && functionToRun,
int priority = 0 )

Definition at line 87 of file qthreadpool.h.

◆ start() [2/2]

void QThreadPool::start ( QRunnable * runnable,
int priority = 0 )

Reserves a thread and uses it to run runnable, unless this thread will make the current thread count exceed maxThreadCount().

In that case, runnable is added to a run queue instead. The priority argument can be used to control the run queue's order of execution.

Note that the thread pool takes ownership of the runnable if \l{QRunnable::autoDelete()}{runnable->autoDelete()} returns true, and the runnable will be deleted automatically by the thread pool after the \l{QRunnable::run()}{runnable->run()} returns. If \l{QRunnable::autoDelete()}{runnable->autoDelete()} returns false, ownership of runnable remains with the caller. Note that changing the auto-deletion on runnable after calling this functions results in undefined behavior.

Definition at line 511 of file qthreadpool.cpp.

◆ startOnReservedThread() [1/2]

template<typename Callable , QRunnable::if_callable< Callable > >
void QThreadPool::startOnReservedThread ( Callable && functionToRun)

Definition at line 103 of file qthreadpool.h.

◆ startOnReservedThread() [2/2]

void QThreadPool::startOnReservedThread ( QRunnable * runnable)

Releases a thread previously reserved with reserveThread() and uses it to run runnable.

Note that the thread pool takes ownership of the runnable if \l{QRunnable::autoDelete()}{runnable->autoDelete()} returns true, and the runnable will be deleted automatically by the thread pool after the \l{QRunnable::run()}{runnable->run()} returns. If \l{QRunnable::autoDelete()}{runnable->autoDelete()} returns false, ownership of runnable remains with the caller. Note that changing the auto-deletion on runnable after calling this functions results in undefined behavior.

Note
Calling this when no threads are reserved results in undefined behavior.
Since
6.3
See also
reserveThread(), start()

Definition at line 784 of file qthreadpool.cpp.

◆ threadPriority()

QThread::Priority QThreadPool::threadPriority ( ) const

Definition at line 738 of file qthreadpool.cpp.

◆ tryStart() [1/2]

template<typename Callable , QRunnable::if_callable< Callable > >
bool QThreadPool::tryStart ( Callable && functionToRun)

Definition at line 93 of file qthreadpool.h.

◆ tryStart() [2/2]

bool QThreadPool::tryStart ( QRunnable * runnable)

Attempts to reserve a thread to run runnable.

If no threads are available at the time of calling, then this function does nothing and returns false. Otherwise, runnable is run immediately using one available thread and this function returns true.

Note that on success the thread pool takes ownership of the runnable if \l{QRunnable::autoDelete()}{runnable->autoDelete()} returns true, and the runnable will be deleted automatically by the thread pool after the \l{QRunnable::run()}{runnable->run()} returns. If \l{QRunnable::autoDelete()}{runnable->autoDelete()} returns false, ownership of runnable remains with the caller. Note that changing the auto-deletion on runnable after calling this function results in undefined behavior.

Definition at line 556 of file qthreadpool.cpp.

◆ tryTake()

bool QThreadPool::tryTake ( QRunnable * runnable)
nodiscard
Since
5.9

Attempts to remove the specified runnable from the queue if it is not yet started. If the runnable had not been started, returns true, and ownership of runnable is transferred to the caller (even when {runnable->autoDelete() == true}). Otherwise returns false.

Note
If {runnable->autoDelete() == true}, this function may remove the wrong runnable. This is known as the \l{https://en.wikipedia.org/wiki/ABA_problem}{ABA problem}: the original runnable may already have executed and has since been deleted. The memory is re-used for another runnable, which then gets removed instead of the intended one. For this reason, we recommend calling this function only for runnables that are not auto-deleting.
See also
start(), QRunnable::autoDelete()

Definition at line 342 of file qthreadpool.cpp.

◆ waitForDone() [1/2]

bool QThreadPool::waitForDone ( int msecs)

Waits up to msecs milliseconds for all threads to exit and removes all threads from the thread pool.

Returns true if all threads were removed; otherwise it returns false. If msecs is -1, this function waits for the last thread to exit.

◆ waitForDone() [2/2]

bool QThreadPool::waitForDone ( QDeadlineTimer deadline = QDeadlineTimer::Forever)
Since
6.8

Waits until deadline expires for all threads to exit and removes all threads from the thread pool. Returns true if all threads were removed; otherwise it returns false.

Definition at line 831 of file qthreadpool.cpp.

Friends And Related Symbol Documentation

◆ QFutureInterfaceBase

friend class QFutureInterfaceBase
friend

Definition at line 30 of file qthreadpool.h.

Property Documentation

◆ activeThreadCount

int QThreadPool::activeThreadCount
read

the number of active threads in the thread pool.

Note
It is possible for this function to return a value that is greater than maxThreadCount(). See reserveThread() for more details.
See also
reserveThread(), releaseThread()

Definition at line 27 of file qthreadpool.h.

◆ expiryTimeout

int QThreadPool::expiryTimeout
readwrite

the thread expiry timeout value in milliseconds.

Threads that are unused for expiryTimeout milliseconds are considered to have expired and will exit. Such threads will be restarted as needed. The default expiryTimeout is 30000 milliseconds (30 seconds). If expiryTimeout is negative, newly created threads will not expire, e.g., they will not exit until the thread pool is destroyed.

Note that setting expiryTimeout has no effect on already running threads. Only newly created threads will use the new expiryTimeout. We recommend setting the expiryTimeout immediately after creating the thread pool, but before calling start().

Definition at line 25 of file qthreadpool.h.

◆ maxThreadCount

int QThreadPool::maxThreadCount
readwrite

the maximum number of threads used by the thread pool.

This property will default to the value of QThread::idealThreadCount() at the moment the QThreadPool object is created.

Note
The thread pool will always use at least 1 thread, even if maxThreadCount limit is zero or negative.

The default maxThreadCount is QThread::idealThreadCount().

Definition at line 26 of file qthreadpool.h.

◆ stackSize

uint QThreadPool::stackSize
readwrite

the stack size for the thread pool worker threads.

The value of the property is only used when the thread pool creates new threads. Changing it has no effect for already created or running threads.

The default value is 0, which makes QThread use the operating system default stack size.

Since
5.10

Definition at line 28 of file qthreadpool.h.

◆ threadPriority

QThread::Priority QThreadPool::threadPriority
readwrite

the thread priority for new worker threads.

The value of the property is only used when the thread pool starts new threads. Changing it has no effect for already running threads.

The default value is QThread::InheritPriority, which makes QThread use the same priority as the one the QThreadPool object lives in.

See also
QThread::Priority
Since
6.2

Definition at line 29 of file qthreadpool.h.


The documentation for this class was generated from the following files: