Threads in Qt

I read on the internet that subclassing (which takes the class out of Qthread) and then overwriting the startup function to do the task you want is not the correct way to use Qthread. But I read in some books and Qt documentation to use the subclassing way?

Can you tell me why you shouldn't use the subclassing way? The Qthread subclass is an easy way to use a thread (for me, because I'm a newbie).

Thank.

+3


source to share


3 answers


QThread was designed and designed to be used as an interface or checkpoint for an operating system thread, not as a place to host the code you want to run on a thread. We are a subclass of object-oriented programmers because we want to extend or specialize the functionality of the base class. The only valid reasons I can think of for subclassing QThread is to add functionality that QThread does not, for example. perhaps providing a memory pointer to use as a thread stack, or perhaps adding interfaces / realtime support. Code to load a file or query a database, or perform any other processing should not be added to the QThread subclass; it must be encapsulated in its own object.

For more details please check this.



http://labs.qt.nokia.com/2010/06/17/youre-doing-it-wrong/

+1


source


Check out this great article on QThread: An excellent QThread Mess by Christoph Eckert that makes me use QThread this way: Threading without the Bradley T. Hughes headache



Bottom line: IMHO, the easiest way to use QThread is to subclass QObject, use signals / slots, and use moveToThread

to make the object live in another thread with a different event loop.
Unfortunately this doesn't work if you absolutely need a stream "while(true)"

, but it can very often be avoided in Qt.

+2


source


The QThread documentation explicitly states that the subclass is correct:

To create your own streams, subclass QThread

and reimplement run()

.

This is somewhat puzzling because (as shobi points out in another answer ) it's an ugly design and there is an alternative solution.

+1


source







All Articles