PDA

View Full Version : Communication/data sharing between threads



Tottish
14th April 2010, 14:15
Hi!

EDIT: SKIP THIS PART I screwed up and it is not an issue anymore.
I'm experiencing some serious difficulties that I perceive as very strange indeed!
I'm programming a multi Thread app and all of a sudden the compiler starts to complain about "xxx" does not name a type when I declare "xxx" under private in my .h file. I can't figure out what the heck the difference is from half an hour ago.

HERE IS THE PROBLEM:
I have two threads (+ a GUI-thread) thread one and thread two.
I can write and read back OK from thread one to Thread twos public variables. But when I try to read them in thread two I get nonesense result: 7.11756e-307.
How could this be?

EDIT2:
When I write to thread twos public vars from the GUI-thread it sticks and is the same when read back from within thread two... Does thread one lack some kind of writing-rights? I think it's strange that it can write and read back the same result, though.
Perhaps it is easier to only use the GUI-thread's public vars for inter threaded communication but I cant seem to get that going either...

Cheers!
/Tottish

Lesiok
14th April 2010, 16:17
If You want to communicate betwen threads with public vars You must synchronise them. Ie. with QMutex (http://doc.trolltech.com/4.6/qmutex.html)

squidge
14th April 2010, 20:45
As Lesiok states, global variables must be suitably protected so that they are only used by one thread at a time otherwise you will see undesired effects. See the QMutex documentation for examples of why and how.

Tottish
15th April 2010, 08:28
Yeah, I've read that but I was lead to believe that this was only necessary when the variables in question had multiple threads that wanted to write to them. Only one of my threads write to a variable and the other threads are strictly readers.
Isn't that true?

/Tottish

EDIT: Tested with mutex. No difference.

Lesiok
15th April 2010, 10:39
Show us some code : declaration of this variables and code accessing them. The glass ball is not working today ;)

squidge
15th April 2010, 13:24
If you have a thread that writes and a thread that reads, you need locking unless the variables are simple types such as 'char'.

Have a look at QReadLocker & QWriteLocker. The former locks for read access, the later locks for write access.

havij000
8th July 2013, 06:33
dear Lesiok,
I have some how such a problem with data sharing with different threads.
but the difference is that when I wanna read a static array in different array they know it by different address :confused: :-??