Qt/C++ - Lesson 047. QThread – How to make threads in Qt

Qt, QThread, потоки

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;
    }
}

Output threads

Video

We recommend hosting TIMEWEB
We recommend hosting TIMEWEB
Stable hosting, on which the social network EVILEG is located. For projects on Django we recommend VDS hosting.
Support the author Donate

Comments

Only authorized users can post comments.
Please, Log in or Sign up
D
Aug. 16, 2019, 11:58 a.m.
Damir

C++ - Тест 003. Условия и циклы

  • Result:92points,
  • Rating points8
D
Aug. 16, 2019, 11:46 a.m.
Damir

C++ - Test 005. Structures and Classes

  • Result:75points,
  • Rating points2
u
Aug. 14, 2019, 1:55 p.m.
unrealproro

C++ - Test 005. Structures and Classes

  • Result:83points,
  • Rating points4
Last comments
Aug. 19, 2019, 6:41 a.m.
Andrej Jankovich

это проблема дистрибутива, попробуйте установить через пакетный менеджер snap Суть проблемы: libQt5Core которая лежит в дистрибутиве требует версию glibc >= 2.25 у вас видимо …
b
Aug. 18, 2019, 5:09 a.m.
bbb116

cqtdeployer /home/aleks/CQtDeployer/bin/cqtdeployer: /lib/x86_64-linux-gnu/libc.so.6: version `GLIBC_2.25' not found (required by /home/aleks/CQtDeployer/lib/libQt5Core.so.5) linux mint …
D
Aug. 17, 2019, 8:04 a.m.
Damir

github ChekableTView Правой групповая смена значения при перетаскивании левой как обычно.
Aug. 16, 2019, 12:03 p.m.
Evgenij Legotskoj

Потому, что в минуте 60 секунд
Aug. 16, 2019, 11:16 a.m.
Dmitrij

а почему делитель 60000, а не 1000?
Now discuss on the forum
Aug. 19, 2019, 10:29 a.m.
Aleksej Vnukov

я в дороге, по тому примеру что в есть выше вам чтоб заработало нужно примерно следующее ListModel{ id: list_model } в ListView добавить model:list_model там где кноп…
Aug. 19, 2019, 8:47 a.m.
Pavel K.

bool YourClass::chekIfEmpty(const QString& table) { return getCount(table) == 0;}int YourClass::getCount(const QString& table, const QString& where) { QString command =…
Aug. 19, 2019, 8:29 a.m.
Pavel K.

посмотрите тут , практически тоже самое делал(пробегал по документу). А так в принципе : QFile file(Path);if(file.exist){ file.open(QIODevice::WriteOnly); // ReadWrite for…
Aug. 19, 2019, 2:39 a.m.
grig_p

Здравствуйте! Хотелось бы в своем приложении сделать цетрализованную обработку исключительных ситуаций для их логирования. Переопределил метод notify(): static const int EC_MAINLOOP…
Aug. 15, 2019, 2:19 a.m.
Mihailll

Плюсы и qml отличаются, с++ логичней
Looking for a Job?
14,000.00 руб. - 40,000.00 руб.
Разработчик Qt
Annino, Moscow Oblast, Russia
5,000.00 руб. - 15,000.00 руб.
Дизайнер
Moskovskiy, Moscow, Russia
25,000.00 руб. - 30,000.00 руб.
Разработчик Qt/C++
Barnaul, Altai Krai, Russia

For registered users on the site there is a minimum amount of advertising

EVILEG
About
Services
© EVILEG 2015-2019
Recommend hosting TIMEWEB