QThread finished () connected to remote QObject element

I thought a lot and read a lot of articles before asking this question here. None of the articles gave me the correct answer.

http://mayaposch.wordpress.com/2011/11/01/how-to-really-truly-use-qthreads-the-full-explanation/

 QThread* thread = new QThread;
 Worker* worker = new Worker();
 worker->moveToThread(thread);
 connect(worker, SIGNAL(error(QString)), this, SLOT(errorString(QString)));
 connect(thread, SIGNAL(started()), worker, SLOT(process()));
 connect(worker, SIGNAL(finished()), thread, SLOT(quit()));
 connect(worker, SIGNAL(finished()), worker, SLOT(deleteLater()));
 connect(thread, SIGNAL(finished()), thread, SLOT(deleteLater()));
 thread->start();

A work object has an affinity for a new thread.

1> The working signal of the completed signal will call quit () in the stream. This will end the flow event loop and initiate the flow of the completed signal.

2> Work signal completed connected to work deleteLater (). According to documentation deleteLater ()

** Specifies this object to delete. The object will be deleted when control returns to the event loop. If the event loop does not work

(, deleteLater() QCoreApplication:: exec()), .

, (, ) ; , , , deleteLater().

. ; , . **

, eventloop, , , . deleteLater() , , . .?

 connect(worker, SIGNAL(finished()), worker, SLOT(deleteLater()));
 connect(worker, SIGNAL(finished()), thread, SLOT(quit()));

, , . QT , , , ,

.

+5
2
//! put the following code in constructor
QThread *thread = new QThread;
//! type of m_weakThread is QWeakPointer<QThread>
m_weakThread = thread;
Worker *worker = new Worker;
//! type of m_weakWorker is QWeakPointer<Worker>
m_weakWorker = worker;
worker->moveToThread(thread);
connect(worker, SIGNAL(error(QString)), this, SLOT(errorString(QString)));
connect(thread, SIGNAL(started()), worker, SLOT(process()));
connect(worker, SIGNAL(finished()), worker, SLOT(deleteLater()));
//! instead of finished() signal, connect destroyed() signal to thread quit() slot
connect(worker, SIGNAL(destroyed()), thread, SLOT(quit()));
connect(thread, SIGNAL(finished()), thread, SLOT(deleteLater()));
thread->start();

//! put the following code in destructor
if (!m_weakThread.isNull()) {
    QThread *thread = m_weakThread.data();
    if (thread->isRunning()) {
        thread->quit();
        thread->wait();
    }
}
if (!m_weakWorker.isNull()) {
    Worker *worker = m_weakWorker.data();
    m_weakWorker.clear();   //! optional, a little optimization
    //! it safe to release worker since the secondary thread exits
    delete worker;
}
if (!m_weakThread.isNull()) {
    QThread *thread = m_weakThread.data();
    m_weakThread.clear();
    //! it safe to release thread since it exits and all objects in it has released
    delete thread;
}
+2

All Articles