I need criticism about how I use the thread class. I have the following files:

#ifndef SOME_THREAD_H #define SOME_THREAD_H #include <QObject> #include <QtCore> class Some_Thread : public QThread { Q_OBJECT public: explicit Some_Thread(QObject *parent = 0) { qDebug() << "Create some thread..."; } void run() { unsigned int count = 0; while(count < 4) { qDebug() << "Thread is doing something..." << count++; this->msleep(500); } } signals: public slots: }; #endif // SOME_THREAD_H 

I launch a flow so:

 #include <QCoreApplication> #include <some_thread.h> int main(int argc, char *argv[]) { QCoreApplication a(argc, argv); Some_Thread *sThread = new Some_Thread(0); QObject::connect( sThread, SIGNAL( finished() ), sThread, SLOT( deleteLater() ) ); sThread->start(); return a.exec(); } 

Questions to you, more experienced colleagues, are as follows:

  1. How to quickly clear the memory after exiting the while loop (count <4)?
  2. Is memory really cleared?
  3. Should the sThread pointer after the deleteLater () execute point to NULL?
  4. How do I reuse this stream?

    1 answer 1

    How to quickly clear the memory after exiting the while loop (count <4)?

    There are several options - call destructors immediately after exiting the loop, call destructors (explicitly or implicitly) in the stream destructor or via deleteLater.

    Is memory really cleared?

    I did not see leaks

    Should the sThread pointer after the deleteLater () execute point to NULL?

    not. it makes no sense. Well, except for its internal logic. This does not affect leakage in the application.

    How do I reuse this stream?

    Likewise - re-create and run.

     Some_Thread *sThread = new Some_Thread(0); QObject::connect( sThread, SIGNAL( finished() ), sThread, SLOT( deleteLater() ) ); sThread->start(); 

    PS I would write a thread constructor at least

     explicit Some_Thread(QObject *parent = 0) : QThread(parent) 
    • and one more question in dogonku, if I do this: QObject :: connect (sThread, SIGNAL (finished ()), sThread, SLOT (deleteLater ())); as far as I understand, then after that it is not necessary to do this: delete sThread ;? - Nikola Krivosheya
    • one
      deleteLater calls delete itself. Therefore, this is not something that is “not necessarily”, but categorically “impossible”. - KoVadim Nov.
    • And under what condition does the signal SIGNAL (finished ()) work? - Nikola Krivosheya
    • one
      Upon completion of the run function - KoVadim Nov.