[Interest] Terminating a QThread
Etienne Sandré-Chardonnal
etienne.sandre at m4x.org
Fri Jun 21 16:32:51 CEST 2013
Hi,
This was my case, but after a careful study of how the event loop and
queued signal/slot connection works, I figured it out and everything works
cleanly now.
It's easy to have this issue, as if you ask the thread to quit via a
signal/slot, you have to ensure that nothing is destroyed or blocked.
For the non-eventloop threads, I just use a quit flag as mentionned, it
works perfectly.
For the eventloop/QObject-worker threads, for instance, I have a
RenderClient, which creates a QThread, a RenderClientPrivate, and makes the
RenderClientPrivate run in the QThread. The RenderClient is then a wrapper
interface for controlling the RenderClientPrivate from the main thread.
Here are definitions/initializations:
RenderClient::RenderClient(QObject * parent)
: QObject(parent), state(Idle)
{
//Create a thread
clientThread = new QThread(this);
//Create a RenderClientPrivate and move it to the new thread
RenderClientPrivate * clientPrivate = new RenderClientPrivate();
clientPrivate->moveToThread(clientThread);
//Destroy the renderer object when the threads exits from event loop
connect(clientThread, SIGNAL(finished()), clientPrivate, SLOT(deleteLater()));
}
RenderClient::~RenderClient(){ debug("RenderClient : destroyed");
//Ensure renderThread finishes its execution as it will be deleted
(child) if(clientThread->isRunning()) { clientThread->quit(); //When
the thread emits finished(), the RenderClientPrivate object will be
deleted, and wait() will
return if(!clientThread->wait(30000)) { warning("RenderClient::~RenderClient
: thread timeout, forced thread to
terminate"); clientThread->terminate(); } }}
That way, the terminate() is never called, and everything gets
destroyed properly.
just to put in my 2 windows cents:
> sometimes my threads even don't stop when i quit() them and a wait() waits
> forever...
>
> so terminate is my only chance for this.
>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.qt-project.org/pipermail/interest/attachments/20130621/f06dac46/attachment.html>
More information about the Interest
mailing list