Important: Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

how to create a new qthread on every call of the function and delete the old one on its completion



  • Hi there is a function 1 on whose call a signal is emitted and a new thread is also created. The connect part in function 1 connects the emitted signal and public slot of another class.

    The thread created in that function 1 should be destroyed after the completion of another class slot.

    And on next call to the function 1 a new thread should be created and so on.

    Currently the thread is not being destroyed. How to fix this i.e. destroy the thread after slot completion.

    Thank You !!!

    void EventListModel::vExtractNextItems()
    {
        emit(fetch());
    
        t = new testthetimer();
    
        workerThread = new QThread();
    
    
        t->moveToThread(workerThread);
    
        connect(this, &EventListModel::fetch, t, &testthetimer::timeout);
    
        qInfo() << "Function 1 call "<< QThread::currentThread();
        workerThread->start();
    
    }
    
    void testthetimer::timeout()
    {
    
        qInfo() << QDateTime::currentDateTime().toString() << " on " << QThread::currentThread();
    
    
    
            qInfo() << "total" << QThread::idealThreadCount();
            this->thread()->quit();
            this->thread()->destroyed();
    
            qInfo() << "running " << this->thread()->isRunning();
            qInfo() << QThread::currentThread();
    }
    

    and the output is

    "Wed Oct 23 17:51:22 2019"  on  QThread(0x7ffe9c803970)
    total 8
    running  true
    current thread is   QThread(0x7ffe9c803970)
    Function 1 call  QThread(0x7ffe9b40efe0)
    qml: DownScale
    "Wed Oct 23 17:51:24 2019"  on  QThread(0x7ffe9b5de260)
    total 8
    running  true
    current thread is   QThread(0x7ffe9b5de260)
    Function 1 call  QThread(0x7ffe9b40efe0)
    

  • Lifetime Qt Champion

    Hi,

    Call deleteLater in your thread.
    Note that the cleaner way to do that is to emit a signal from your class and connect that to the QThread deleteLater method. This avoids that class to do any thread management that it should not really care about.

    Depending on your use case, you might want to consider the use of QtConcurrent.


  • Lifetime Qt Champion

    Hi,

    Call deleteLater in your thread.
    Note that the cleaner way to do that is to emit a signal from your class and connect that to the QThread deleteLater method. This avoids that class to do any thread management that it should not really care about.

    Depending on your use case, you might want to consider the use of QtConcurrent.



  • yes but with QtConcurrent. i am facing other problems please refer to https://forum.qt.io/topic/108088/how-to-replace-qthread-with-qtconcureent


Log in to reply