[Qt-interest] QThread Question

Sean Harmer sean.harmer at maps-technology.com
Thu Aug 6 13:00:13 CEST 2009


Hi,

On Thursday 06 Aug 2009 11:43:01 Donal O'Connor wrote:
> Hi,
>
> I've got code here written by somebody else that seems to make use of
> several threads but I'm quite worried that the processing is not done in a
> different thread like intended.
>
> They've created an object derieved from QThread but never implemented the
> run method so it defaults to the exec() event state when started.
> Now, they've created slots and these slots by the looks of it does the hard
> work which to the best of my knowledge results them being run in the
> calling thread.
>
> Am I correct in saying, that if you call a method of a QThread object or
> arrive at a slot due to a Queued connection that the processing done in the
> slot/method
> is done in the calling thread and not in the actual thread that was stared
> for the QThread object?
>
> To the best of my knowledge, the way it should be done, is all the
> processing done in the run() method but use the methods/slots to change
> data/state of thread of the thread but using Mutex's since it's the calling
> thread that will be modifying the data and should be mutually exclusive
> from the run method which reads or writes to this data.
>
>
> Am I correct in what I'm saying here? - Apologies if it's obvious but this
> code I'm looking at is starting to confuse me.
I think that this approach will run the slots in the worker thread iff:

* The QThread object has thread-affinity with itself. i.e. you have to call 
moveToThread( myThread ) where myThread is your QThread object. If the thread 
is not moved to itself, then it still has affinity with the main thread since 
that is where it was created. In this situation the slots would be executed in 
the main thread.

* You use QueuedConnection or BlockingQueuedConnection types in your connect 
calls. If you make all of your connections after the thread object has been 
moved to its own thread then the connect statement should work this out for 
you. The section in the docs called "Signals and Slots Across Threads" 
explains this.

HTH,

Sean



More information about the Qt-interest-old mailing list