Terminate QThread correctly
Locked
Unsolved
Mobile and Embedded
-
Hi everybody,
I've a doubt about how to correctly close a QThread.
I've read the QThread Basics docs and also had a look on StarckOverflow and the Qt forum, but still having the doubt.I've implemented many htread-worker threads, and they all work correctly. The only problem is when I delete the thread: I always get "QThread: destroyed while thread is still running".
Putting a "wait()" call after the "terminate()" one, never exit since it remains pending waiting for the thread termination.Here a bit of my code:
/* THIS IS THE CREATION OF THE THREAD CONTROLLER AND THE WORKER */ QThread *threadController = new QThread(this); // ThreadWorker is my custom class ThreadWorker* threadWorker = new ThreadWorker( ); threadWorker->moveToThread( threadController ); connect( threadController , SIGNAL(started()), threadWorker, SLOT(Work()), Qt::QueuedConnection ); threadController ->start();
Here the implementation of the custom class
/* ThreadWorker.h */ class ThreadWorker : public QObject { Q_OBJECT public: ThreadWorker(); ~ThreadWorker(); public slots: void Work(); void onAbort(); private: bool thread_exit; }; /* ThreadWorker.cpp */ // Constructor ThreadWorker::ThreadWorker() { this->thread_exit = false; } // Destructor ThreadWorker::~ThreadWorker() { } // "Main" function void ThreadWorker::Work() { // Thread loop while( !this->thread_exit ) { // Wait sleep(1); // Do some actions.. // Process application events QCoreApplication::processEvents( QEventLoop::AllEvents ); } } // Stop thread void ThreadWorker::onAbort() { // Exit thread loop this->thread_exit = true; }
I'm using Qt 4.8 on a iMX6SX board with Yocto Dizzy distro.
Many thanks
Andrea[Locked as duplicate of https://forum.qt.io/topic/84466/terminate-qthread-correctly ~kshegunov]