What QReadLocker guarantee?

  • Hi,

    I've a global static array and two threads use the data from the array for purposes. One thread(threadA) just find the array index(QHash<>) and update the data, whereas other thread(threadB) just read the same array.Since, threadA gets data from network which is not predictable and threadB which basically polls the data at some interval, but done outside the application.

    I'm using QReadLocker(threadB) and QwriteLocker(threadA).So, my doubt is like, If threadA is doing some update operation on the global array, will the threadB get block or get inconsistent data during polling.

  • The sole purpose of QReadLocker, QWriteLocker and QReadWriteLocker is to synchronize read and write access. As long as a write lock is active, read attempts are blocked. As long as read blocks are active, a write attempt is blocked.

  • Well, then what is the difference in using Qmutex and QReadLocker, QWriteLocker , QReadWriteLocker. Is that the name which can remove the confusion from developer who is using it. Like, QReadLocker is associated with read and QWriteLocker associate with write. Rather than giving our own name for QMutex(eg QMutex readMutex.. etc).

    So, plz tell me which mechanism can I use for the above scenario,

  • The difference is, that a QReadLocker will not block another QReadLocker.

  • To cite the docs of QReadWriteLock:

    bq. In many cases, QReadWriteLock is a direct competitor to QMutex. QReadWriteLock is a good choice if there are many concurrent reads and writing occurs infrequently.

    bq. Qt 4 also introduces a new synchronization class: QReadWriteLock. It is similar to QMutex, except that it distinguishes between "read" and "write" access to shared data and allows multiple readers to access the data simultaneously. Using QReadWriteLock instead of QMutex when it is possible can make multithreaded programs more concurrent.

    So, while QMutex ensures that only one single thread can access the data at a given time, regardless of read or write access, the QReadWriteLock and friends grant unlimited read access but ensure that only one single thread can write the data at a given time and block all read attempts during this time.

  • As Andre and Volker said, the Q{Read|Write|ReadWriter}Lock classes and their (*Locker classes which you should use) allow more fine-grained control over your locks to minimise lock contention and therefore hopefully let you application be more concurrent.

Log in to reply

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.