How Qt5.9 inherits QObject to create multithreading
This article is to share with you about how Qt5.9 inherits QObject to create multithreading, the editor thinks it is very practical, so I share it with you to learn. I hope you can get something after reading this article.
Using the inherited QObject method to create multithreading, the main steps are as follows: (note: after exiting the thread loop, the QThread::quit () function is called before the thread triggers the QThread::finished () signal.)
A1: first create a class MyThread, and the base class is QObject.
A2: create a slot function in the class MyThread to run the code in multithreading. All the time-consuming code runs in this slot function.
A3: instance a QThread thread object (container), transfer the instance object of class MyThread to this container, and use the function void QObject::moveToThread (QThread * thread)
MyObjectThread- > moveToThread (firstThread)
A4: trigger the multithreaded slot function with a signal, such as the QThread::started () signal.
Connect (firstThread,SIGNAL (started ()), myObjectThread,SLOT (startThreadSlot ()
A5: use the signal QThread::finished to bind the slot function QThread::deleteLatater () to destroy the thread and related resources when it exits.
Connect (firstThread,SIGNAL (finished ()), firstThread,SLOT (deleteLater ()
A6: after all threads are initialized, the startup function QThread::start () starts multithreading, and then automatically triggers the multithreading startup signal QThread::started ().
The specific tutorial is shown in the following figure:
1.1 create a new widget project, do not check the ui interface. Then add the following code to mythread.h,mythread.cpp,widget.h,widget.cpp,main.cpp respectively.
Mythread.h
# ifndef MYTHREAD_H#define MYTHREAD_H# include class MyThread: public QObject {Q_OBJECTpublic: explicit MyThread (QObject * parent = nullptr); void closeThread (); signals: public slots: void startThreadSlot (); private: volatile bool isStop;}; # endif / / MYTHREAD_H
Mythread.cpp
# include "mythread.h" # include # include MyThread::MyThread (QObject * parent): QObject (parent) {isStop = false;} void MyThread::closeThread () {isStop = true;} void MyThread::startThreadSlot () {while (1) {if (isStop) return; qDebug ()