PDA

View Full Version : QThread - Using a slot to exit the thread



johnnyturbo3
26th April 2011, 13:23
Hi,

I want to inform an object when a thread has finished running. However, I cannot get the thread to exit properly. I have the following code:

Processor.cpp


thread = new QThread;
tw = new ThreadWorker;
connect(tw, SIGNAL(updateStatus(QString)), this, SLOT(statusUpdate(QString)));
tw->doSetup(thread, strDic);
tw->moveToThread(thread);
thread->start();

while(thread->isRunning())
{
}

qDebug() << "Thread Finished";


ThreadWorker.cpp


void ThreadWorker::doSetup(QThread *thread, const string &path)
{
_strPath = path;
connect(thread, SIGNAL(started()), this, SLOT(run()));
connect(this, SIGNAL(finished()), thread, SLOT(quit())); //tried terminate() also
}


void ThreadWorker::run()
{
DirectorySearch dicSearch;
vector<string> vecFileList = dicSearch.getFileList(_strPath);
emit updateStatus("Directory Fetched");
emit finished();
}

The quit() slot does not seem to stop the thread (QThread::isFinished never returns true). Can someone guide me in the right direction?

Thanks in advance

mcosta
26th April 2011, 13:26
Have you called ThreadWorker::exec() ??

If you don't ThreadWorker doesn't launch eventLoop and so doesn't receive signals

johnnyturbo3
26th April 2011, 13:28
The ThreadWorker class doesn't inherit from QThread. So it has no exec() method.

mcosta
26th April 2011, 14:20
Is ThreadWorker derived from QObject?

can you post ThreadWorker definition (header file)?

johnnyturbo3
26th April 2011, 14:24
class ThreadWorker : public QObject
{
Q_OBJECT

public:
ThreadWorker(void);
~ThreadWorker(void);


void doSetup(QThread *, const string &);

public slots:
void run();

signals:
void updateStatus(QString);
void finished();

private:
DirectorySearch dicSearch;
string _strPath;
};

mcosta
26th April 2011, 15:07
When you call QObject::moveToThread, you obtain some warning messages in console?

Do you tried to start the thread before to move ThreadWorker?

johnnyturbo3
27th April 2011, 08:27
I think I understand what's happening now.

The main thread is being kept busy by the
while(thread->isRunning())
{
}

Therefore, it cannot process any signals being sent by the ThreadWorker.cpp

mcosta
27th April 2011, 11:36
;)

I thought that you omitted some line of code



while(thread->isRunning())
{
...
}


PS. As general rule isn't correct to wait thread termination in this way.