P
P
Pavel K2016-09-19 02:28:58
Qt
Pavel K, 2016-09-19 02:28:58

Implementation of QThread in Qt - is it correct and what are the pitfalls?

Greetings!
I am making an implementation of a class that should process data in the background.
It turned out like this:
Header:

class MyThread : public QObject
{
    Q_OBJECT
public:
    explicit MyThread(QObject *parent);
    ~MyThread();

    void process();

signals:
    void finished();

public slots:
    void start();
    void stop();

private:
    QThread * _thread;
    bool _started;
};

Implementation:
#include "mythread.h"

MyThread::MyThread(QObject * parent)
    :QObject(0) //-- у нас не должно быть родителя т.к. мы в другом потоке
{
    Q_ASSERT(parent!=0);
    qDebug()<<"MyThread created";
  
    _started = false;

    _thread = new QThread(0); //-- сам поток не должен иметь родителя, что бы он не снёс его ненароком, пока поток выполняется

    connect(_thread, &QThread::started, this, &MyThread::process); //-- при запуске потока сразу начинаем работу
    connect( this, &MyThread::finished, _thread, &QThread::quit ); //-- как только вся работа сделана или остановлена, останавливаем поток
    connect(_thread, &QThread::finished, this, &QObject::deleteLater ); //-- как только поток закончен удаляемся
    connect(this, &QObject::destroyed, _thread, &QThread::deleteLater ); //-- Как только удалились, удаляем сам поток
    connect(parent, &QObject::destroyed, this, &MyThread::stop); //-- как только родитель удаляется, останавливаем поток

    moveToThread(_thread);
}


void MyThread::process()
{
    while (true) {

        if (!_started) { break; }

        QApplication::processEvents(); //-- курим бамбук
    }

    emit  finished();
}

void MyThread::start()
{
    qDebug()<<"MyThread start";

    _started = true;
    _thread->start();
}

void MyThread::stop()
{
    qDebug()<<"MyThread stop";

    if (!_started) { //-- если мы ещё не запускались, то просто удаляемся
        this->deleteLater();
    }

    _started = false;
}


MyThread::~MyThread()
{
    qDebug()<<"MyThread deleted";
}

I call accordingly: I saw a bunch of articles on the Internet: inheritance directly from QThread, "Proper use of QThread" from Habr, etc. For the most part, everyone didn’t like the fact that you need to write an additional wrapper directly to the class, either a separate class, or write new QThread(), moveToThread next to it, then monitor all threads, etc. Tell me, is the implementation of creating, starting, stopping and deleting a thread and class normal, if not, why not? What are the pitfalls in it?
_myThread = new MyThread(this);

Answer the question

In order to leave comments, you need to log in

1 answer(s)
R
Rou1997, 2016-09-19
@Rou1997

I don’t see any implementation, the code does nothing, so I can’t answer, even if he smokes bamboo!

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question