[Qt-interest] Basic QThread question

Phil phillor at telstra.com
Tue May 18 09:34:46 CEST 2010


On Mon, 17 May 2010 06:30:27 pm Sean Harmer wrote:
> Hi Phil,
> 
> According to the above you are creating an instance of Class_A on the 
stack
> and it will be destroyed at the end of the Pest::selectItem() function. Is
> that really the case or do you mean that classA is a member variable of 
the
> Pest class?

Yes, it's a member variable.

> 
> The usual way to share objects between threads is to use a pointer or a
> reference. So you could add a Class_A* member to the DevicePoller class 
and
> set this before you start the poller.
> 
> You need to be slightly careful though because if you are accessing an
>  object from more than one thread you then introduce the possibility of
>  race conditions etc. If you have the source for Class_A then you will be
>  best to protect the data members of Class_A from simultaneous access 
from
>  multiple threads by using a QMutex or similar. Depending upon how 
complex
>  Class_A is this could get complicated.
> 

It is already complicated, and quickly getting beyond my limited 
programming ability.

> A much easier way is to try to avoid having multiple threads access 
Class_A
>  at all. For example what you could do is call Class_A::getData() in a slot
>  that runs in your main thread in response to the value(int) signal being
>  emitted by your polling thread. That way you only need the single 
instance
>  of Class_A - the one in the main thread.

This is exactly what I'm doing but the hardware has many write functions 
besides a data reading function. I'm attempting to write to the hardware 
from the main thread which intermittently conflicts with the read from the 
DevicePoller thread. Precisely the simultaneous access condition that you 
mentioned above. 
 
> It is difficult to say which approach is better for you without knowing
>  what Class_A actually does and how long the Class_A::getIntitialValues()
>  and getData() functions take. If possible I would go with the second
>  option as it removes the possibility of concurrency issues within Class_A.
> 

Before receiving your reply Sean I was nearing the point of giving up on 
threads and going back to my GUI blocking version. It seems to me that I 
need to combine the hardware's write functions, which are currently 
members of the main class, and the read function into your DevicePoller 
class. I'm unsure just how I might access the write functions from the main 
class without causing a simultaneous access condition. The best that I come 
up with is:

if(OkToRead)
    readDevice();

> No problem. If you still run into trouble, come back with more details on
> Class_A.

I'm hesitant to burden the other list members with this seemingly never 
ending saga. I'll see if I can approach this problem from a different angle.

-- 
Regards,
Phil



More information about the Qt-interest-old mailing list