One of the most common ways to create a separate parallel threads in an application to Qt , and perform useful tasks in them is the inheritance of QThread class and override the method run() , which will be carried out and useful application code. When meeting with threads have read different opinions on this subject, and in this lesson will get acquainted with one of the possible ways to work with streams, but which are not considered to be the best option.
In general, if we make the class inherit from the QThread , it is logical to assume that this is done with the intention that it is not sufficient functionality of the class. But when this is done only with the aim to bring in, which must be performed in a separate thread run() method a useful code, then there is clearly something wrong. In addition, de might be a problem with scaling applications and reuse code, particularly hard this can be shown in the case where such inherited class becomes quite a lot.
This method is the low level, and is used primarily for customization native streams. What is somewhat contrary to the usual need to complete a task in a separate thread. That is, as mentioned above, such an approach is primarily needed to extend the functionality class. Nevertheless, this method is necessary to consider what and proceed.
main.cpp
This example is very small, so we will not go into the details of the project structure. Note that there will be created a console application in the file main.cpp which will create three streams with different names. A stream classes will be inherited from QThread .
#include <QCoreApplication> #include "examplethreads.h" int main(int argc, char *argv[]) { QCoreApplication a(argc, argv); ExampleThreads threadA("thread A"); ExampleThreads threadB("thread B"); ExampleThreads threadC("thread C"); threadA.start(); // Run threads threadB.start(); // and seeing their parallel operation threadC.start(); // in the output qDebug return a.exec(); }
examplethreads.h
#ifndef EXAMPLETHREADS_H #define EXAMPLETHREADS_H #include <QThread> class ExampleThreads : public QThread { public: explicit ExampleThreads(QString threadName); // Override run () method, which will be located // executable code void run(); private: QString name; // thread name }; #endif // EXAMPLETHREADS_H
examplethreads.cpp
#include "examplethreads.h" #include <QDebug> ExampleThreads::ExampleThreads(QString threadName) : name(threadName) { } void ExampleThreads::run() { for (int i = 0; i <= 100; i++ ) { qDebug() << name << " " << i; } }