Terminating all threads.
-
First of all, hello everyone, I'm new here and hope I'll learn much about Qt, because I really liked it :-)
I'm using VoidRealm's video tutorials in Qt, I'm stuck on Multi-threaded server.
I'm trying to collect all the threads with QList<QThread*> blabla and using foreach macro exit all of them, but I got stuck.Here's code.
[code]//tcpserver.h
.....
private:
QList<QThread*> client_thread;[/code][code]//tcpserver.cpp
void TCPServer::incomingConnection(int handle)
{
Thread *thread = new Thread(this);
client_thread.append(thread);
thread->socketDescriptor = handle;
connect(thread, SIGNAL(finished()), thread, SLOT(deleteLater()));
thread->start();
}void TCPServer::stopServer()
{
this->close();
foreach(QThread *term_thread, client_thread)
{
term_thread->exit(0);
}
}[/code]
Thanks. :) -
Not exactly sure what your problem is.
But in general you should not terminate threads, using QThread::terminate() because it may terminate the thread at an arbitrary position, which could result in resources not being freed up properly or data being left in inconsistent state (and other evil side-effects). Instead, use QThread::wait() to wait for the thread to terminate. Do this for all the QThread objects that you have in your QList<QThread*> list and you can be sure they all have been terminated - given that the list is complete. In addition to that, you might want to have a global "terminate" flag, which you set to TRUE as soon as you want your threads to terminate. The code executed by each thread should then check that flag at regular intervals and exit as soon as possible (but cleanly!), when the flag is set.
@volatile bool g_terminate = false;
QList<QThread*> client_thread;
//Main Thread
void TCPServer::stopServer(void)
{
[...]//tell all threads to terminate asap g_terminate = true; //Wait until all threads have finished foreach(QThread *term_thread, client_thread) { bool ok = term_thread->wait(5000); //Thread did not terminate (timeout), probably deadlocked! if(!ok) { qWarning("Thread is deadlocked, going to terminate, expect trouble!"); thread->terminate(); thread->wait(); } }
}
//Worker Thread(s)
void MyThread::run(void)
{
while(moreWorkLeft && !g_terminate)
{
doSomeWork();
}
}
@