PDA

View Full Version : How to destroy or terminate a thread ?



probine
26th December 2006, 11:30
I have a program that every time a client connects to the server, a new thread is created for that client.

When the login has been unsuccessful, then the server should destroy the thread that was created to handle that client.

How do I destroy the thread or terminate it ? so when the client wants to try to login again, a new thread will handle it ?

jpn
26th December 2006, 13:43
The execution of the thread ends when the control returns from QThread::run(). If the thread is running an event loop, it can be quit by QThread::quit(). It might be a good idea to delete the thread object as well, at least if the server is expected to run for a long time. Otherwise the memory is not freed until the application quits (supposing the thread objects are children of the server object).

probine
26th December 2006, 16:41
My application consists of a server an a client. The server creates a thread every time a new client connects to it. This created thread handles all the logic with the client.

When the client disconnects, then the thread should stop and also be deleted from memory.

How ?

wysota
26th December 2006, 16:44
Simply return from run(). Just remember to delete the thread object if it was created on heap or you may starve your system. Alternatively you could implement a queue of threads waiting for requests to be handled instead of spawning new threads each time and terminating them afterwards.