[Qt-interest] Proper way to terminate QThreads

Mihail Naydenov mlists at ymail.com
Tue Nov 17 19:01:01 CET 2009





----- Original Message ----
> From: BRM <bm_witness at yahoo.com>
> To: qt-interest at trolltech.com
> Sent: Tue, November 17, 2009 7:19:20 PM
> Subject: [Qt-interest] Proper way to terminate QThreads
> 
> I have several programs in which I am using QThread derived objects to do some 
> working, mostly handling network connections. The basic structure is as follows:
> 
> myThread - derived from QThread
> myThreadInstance - class that does the work; instantiated via myThread::run()
> 
> myThread is pretty much just a signals, with myThreadInstance having signals and 
> slots.
> The main program starts the thread using myThread->start().
> 
> I am presently having a small issue with one program that handles network 
> connections using this threading setup - I receive a network connection from a 
> QTcpServer instance and hand it off to a thread to manage. However, I need to 
> cancel the thread when the connection goes away after I notify the main thread 
> (so that it can initiate the cancel).
> 
> What is the proper way to cancel the thread?
> 
> I've noticed in the documentation that there is QThread::quit() and 
> QThread::terminate(); however, I thought I remember reading somewhere that those 
> should only be called from within the thread being terminated - not from a 
> parent thread.
> What's the proper method for stopping these threads?

As said in the docs, if and when you return from run() the thread is stoped.
The two ways to do that are:
1 quit() - will work only if you start the eventLoop of the thread, calling exec() from run. You can call them form anywhere, its a slot.
2 The other method, the one that every sample code in Qt uses, is to have a loop in your run() that waits on work, and while doing work check for an "abort variable" and if it is set - return from run(). (see threads/mandelbrot example)

Note that the second method is easier to grasp, but the first might be easier to implement, because you do not have to derivate a new QThread!
The only requirement is to do all your work in a slot of some qobject!
Just create a QThread instance, move your regular qobject to it, and start() the thread.
Now if you call the (work doing) slot from some signal (not directly through . or -> but let a signal call it), the work will be done in the new thread.
After you are done call quit().

to Qt team
Please, add a sample code that uses the second method! It took me a while to find out, how can I do useful work *without* actually doing it all in run().

MihailNaydenov

> 
> Thanks!
> 
> Ben
> 
> _______________________________________________
> Qt-interest mailing list
> Qt-interest at trolltech.com
> http://lists.trolltech.com/mailman/listinfo/qt-interest



      



More information about the Qt-interest-old mailing list