PDA

View Full Version : Does a QReadWriteLock need to be the same in order to be valid?



Momergil
29th May 2014, 19:54
Hello!

I have implemented an application where, apart from the main thread, there are two other threads that access the same QVector: one only writes into it while the other reads and erase (QVector::clear()). In order to prevent problems, I created a QReadWriteLock on each of the two classes and I call them when needed (either for "lockForWrite()" in the first thread or "lockForRead()" in the second).

The problem is that, while debugging, I found out that after calling the lockForRead() and inside its scope the QVector was actually being edited by the first thread (which had itself called lockForWrite() before doing that). In other words, the locking wasn't working \o/

So does this means that, in order for the locking mechanism to work, I need to always consider the same locker? In other words, I must either declare one of the lockers as public and access it from the other thread or else use "extern" to access it? And is this valid also for mutexes?


Thanks,

Momergil

Rafaelfsilva
29th May 2014, 20:05
Hi!

You really need to use only one Mutex/Locker, using two mutexes/lockers would mean that you want to lock the access to other objects or following another logic.

As you may know, lock for reading allows more than one thread to read it at a time. Lock for writing will allow only one thread to write. But this applies only if you're using the same locker.

stampede
29th May 2014, 20:27
(...) two other threads that access the same QVector: one only writes into it while the other reads and erase (QVector::clear()).

"lockForWrite()" in the first thread or "lockForRead()" in the second
This looks like a bug to me. Both threads are modifying the same data structure ("clear" is also a kind of "write", as it changes the object), and without proper synchronization you have a race condition here - simply use QMutex in both threads to solve this. Or use read/write lock but "clear" only in the first thread.

anda_skoa
30th May 2014, 12:10
I created a QReadWriteLock on each of the two classes

Just to sure sure: you only have one instance of the lock that you share between the instances of the classes involved in accessing the vector?

Cheers,
_

Momergil
30th May 2014, 14:26
Just to sure sure: you only have one instance of the lock that you share between the instances of the classes involved in accessing the vector?

Cheers,
_

Actually not: the situation, as correctly interpreted by the other two commentators, was that I had two lockers, one defined on each thread's private section in the header file. No wonder why I experienced some crashes :)

But situation was normalized and now I noticed the locking mechanism is working correctly.


Thanks,

Momergil