How to do it…

Let's get started by performing the following steps:

  1. Create a new Qt Widgets Application project and create a new C++ Class called MyProcess, which inherits the QRunnable class. 
  2. Next, open up myprocess.h and add the following headers:
#include <QRunnable>
#include <QDebug>
  1. Then, declare the run() function, as follows:
class MyProcess : public QRunnable {
public:
MyProcess();
void run();
};
  1. After that, open up myprocess.cpp and define the run() function:
void MyProcess::run() {
int myNumber = 0;
for (int i = 0; i < 100000000; ++i) {
myNumber += i;
}
qDebug() << myNumber;
}
  1. Once you're done, add the following headers to mainwindow.h:
#include <QMainWindow>
#include <QThreadPool>
#include "myprocess.h"

  1. After that, we will implement the class constructor by adding the following code:
MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow) {
ui->setupUi(this);

MyProcess* process = new MyProcess;
MyProcess* process2 = new MyProcess;
MyProcess* process3 = new MyProcess;
MyProcess* process4 = new MyProcess;

QThreadPool::globalInstance()->start(process);
QThreadPool::globalInstance()->start(process2);
QThreadPool::globalInstance()->start(process3);
QThreadPool::globalInstance()->start(process4);

qDebug() << QThreadPool::globalInstance()->activeThreadCount();
}
  1. Now, build and run the project. You should see that the processes are successfully being run in different threads where the active thread count is four.
  2. The QThreadPool class automatically deactivates threads when its last process has been executed. Let's try and prove that by pausing the program for three seconds and printing out the active thread count again:
qDebug() << QThreadPool::globalInstance()->activeThreadCount();
this->thread()->sleep(3);
qDebug() << QThreadPool::globalInstance()->activeThreadCount();
  1. Build and run the program again. This time, you should see that the active thread count is four, and then, after three seconds, the active thread count becomes zero. This is because all of the processes have been executed.
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset