Qt
Internal/Contributor docs for the Qt SDK. <b>Note:</b> These are NOT official API docs; those are found <a href='https://doc.qt.io/'>here</a>.
Loading...
Searching...
No Matches
QReadWriteLock Class Reference

\inmodule QtCore More...

+ Collaboration diagram for QReadWriteLock:

Detailed Description

\inmodule QtCore

The QReadWriteLock class provides read-write locking.

\threadsafe

A read-write lock is a synchronization tool for protecting resources that can be accessed for reading and writing. This type of lock is useful if you want to allow multiple threads to have simultaneous read-only access, but as soon as one thread wants to write to the resource, all other threads must be blocked until the writing is complete.

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.

Example:

void ReaderThread::run()
{
...
lock.lockForRead();
read_file();
lock.unlock();
...
}
void WriterThread::run()
{
...
lock.lockForWrite();
write_file();
lock.unlock();
...
}

To ensure that writers aren't blocked forever by readers, readers attempting to obtain a lock will not succeed if there is a blocked writer waiting for access, even if the lock is currently only accessed by other readers. Also, if the lock is accessed by a writer and another writer comes in, that writer will have priority over any readers that might also be waiting.

Like QMutex, a QReadWriteLock can be recursively locked by the same thread when constructed with \l{QReadWriteLock::Recursive} as \l{QReadWriteLock::RecursionMode}. In such cases, unlock() must be called the same number of times lockForWrite() or lockForRead() was called. Note that the lock type cannot be changed when trying to lock recursively, i.e. it is not possible to lock for reading in a thread that already has locked for writing (and vice versa).

See also
QReadLocker, QWriteLocker, QMutex, QSemaphore

The documentation for this class was generated from the following file: