Qt thread pool QThreadPool class, QRunnable class

QThreadPool class

Used to manage QThreads. All functions in this class are thread-safe.

Main attributes:

1. activeThreadCount: This attribute indicates the number of active threads in the thread pool, which is called by activeThreadCount().

2. expiryTimeout: The time the thread is alive. Threads with no expiryTimeout milliseconds set will automatically exit, and such threads will be restarted as needed. The default expiryTimeout is 30000 milliseconds (30 seconds).

The benefits of this article,Fees to receive Qt development learning materials package, technical video, including (Qt actual combat project, C ++ language foundation, C ++ design pattern, introduction to Qt programming , QT signal and slot mechanism, QT interface development-image drawing, QT network, QT database programming, QT project combat, QSS, OpenCV, Quick module, interview questions, etc.) ↓↓↓↓↓↓See below↓↓Click at the bottom of the article fee collection↓↓

If expiryTimeout is negative, newly created threads will not expire and they will not exit until the thread pool is destroyed. Called by expiryTimeout(), set by setExpiryTimeout(int expiryTimeout).

3. maxThreadCount: int indicates the maximum number of threads used by the thread pool.
Called by maxThreadCount(), set by setMaxThreadCount(int maxThreadCount)
Note: Even if the maxThreadCount limit is zero or negative, the thread pool has at least 1 thread.

primary member function

QThreadPool *QThreadPool::globalInstance()

Returns the Qt application global thread pool instance.

void reserveThread()

Reserve a thread, this function will always increase the number of active threads. This means that by using this function, activeThreadCount() can return a value greater than maxThreadCount().

void releaseThread()

Releases a thread previously reserved by calling reserveThread().
Calling this function will temporarily increase maxThreadCount() if a thread is not reserved first. When a thread goes to sleep waiting, other threads can be allowed to continue.
Remember to call reserveThread() when you are done waiting so that the thread pool can properly control activeThreadCount().

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

When the number of tasks is less than maxThreadCount, reserve a thread for each runnable task. When maxThreadCount is exceeded, put the task in the run queue. The priority parameter is used to set the thread running priority.

bool tryStart(QRunnable *runnable)

This method attempts to reserve a thread to run the runnable.
If no threads are available at the time of the call, this function does nothing and returns false. Otherwise, the runnable is run immediately using one of the available threads, and this function returns true.

void clear()

Used to delete tasks that have not been started in the task queue.

bool tryTake(QRunnable *runnable)

If the runnable task has not started running, then delete the runable task from the queue, at this time the function returns true; if the runnable task has already run, returns false.
It is only used to delete runnable tasks with runnable->autoDelete() == false, otherwise the wrong task may be deleted.

bool waitForDone(int msecs = -1)

Waits msecs milliseconds for all threads to exit and removes all threads from the thread pool. Returns true if all threads are removed, otherwise, it returns false. The default wait time is -1, which means waiting for the last thread to exit.

QRunnable class

The QRunnable class is the base class for all runable objects.
The QRunnable class is an interface used to represent tasks or code segments that need to be executed, and the specific tasks are implemented inside the run() function.
You can use QThreadPool to execute code in separate threads. If autoDelete() returns true (the default), QThreadPool will automatically delete the QRunnable. Use setAutoDelete() to change whether to delete automatically.

primary member function

bool autoDelete() const

Get whether automatic deletion is enabled, return true if enabled, and return false if not enabled.

virtual void run() = 0

The pure virtual function implements the detailed task processing logic in the QRunnable subclass.

void setAutoDelete(bool autoDelete)

If autoDelete is true, automatic deletion is enabled. Otherwise automatic deletion will be disabled.
If auto-deletion is enabled, QThreadPool will automatically delete this runable object after calling the run() function to return. Otherwise, the ownership of the runable object does not belong to the thread pool and is managed by the developer.
Note that this flag must be set (it is already set to true by the default constructor) before calling QThreadPool::start(). Calling this function after QThreadPool::start() will have unpredictable results.

Calling this function will have unpredictable results.

program:

Task class (runable class) header file

#ifndef PRINTTASK_H
#define PRINTTASK_H

#include <QObject>
#include <QRunnable>

class PrintTask : public QObject, public QRunnable
{
    Q_OBJECT

public:
    PrintTask();
    ~PrintTask();
protected:
    void run();

signals:
    //Notice! To use signals, use QObejct and QRunnable multiple inheritance, remember that QObject should be placed in front
    void mySignal();
};

#endif // PRINTTASK_H

Task class (runable class) implementation file

#include "printtask.h"
#include <QThread>
#include <iostream>
using std::cout;
using std::endl;

PrintTask::PrintTask()
{
}

PrintTask::~PrintTask()
{

}

//What the thread actually executes
void PrintTask::run()
{
    cout << "PrintTask run is called, the calling thread ID is: " << QThread::currentThread() << endl;
}

Main function file:

#include <QCoreApplication>
#include <QThreadPool>
#include "printtask.h"

int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);

    //Set a thread pool with a maximum number of threads of 3
    QThreadPool pool;
    pool.setMaxThreadCount(3);

    for(int i = 0; i < 20; i ++ )
    {
        pool.start(new PrintTask());
    }

    return a.exec();
}

output:

PrintTask run is called, and the calling thread ID is: 00533678
PrintTask run is called, and the calling thread ID is: 00533678
PrintTask run is called, and the calling thread ID is: 004F3868
PrintTask run is called, and the calling thread ID is: 004F3848
PrintTask run is called, and the calling thread ID is: 00533678
PrintTask run is called, and the calling thread ID is: 00533678
PrintTask run is called, and the calling thread ID is: 004F3848
PrintTask run is called, and the calling thread ID is: 004F3868
PrintTask run is called, and the calling thread ID is: 00533678
PrintTask run is called, and the calling thread ID is: 00533678
PrintTask run is called, and the calling thread ID is: 004F3848
PrintTask run is called, and the calling thread ID is: 00533678
PrintTask run is called, and the calling thread ID is: 004F3868
PrintTask run is called, and the calling thread ID is: 004F3848
PrintTask run is called, and the calling thread ID is: 00533678
PrintTask run is called, and the calling thread ID is: 004F3868
PrintTask run is called, and the calling thread ID is: 004F3848
PrintTask run is called, and the calling thread ID is: 004F3868
...
...

After analyzing the print results, it is found that there are only 3 threads (thread IDs are 00533678, 004F3848, and 004F3868) to execute 20 tasks.

The benefits of this article,Fees to receive Qt development learning materials package, technical video, including (Qt actual combat project, C ++ language foundation, C ++ design pattern, introduction to Qt programming , QT signal and slot mechanism, QT interface development-image drawing, QT network, QT database programming, QT project combat, QSS, OpenCV, Quick module, interview questions, etc.) ↓↓↓↓↓↓See below↓↓Click at the bottom of the article fee collection↓↓