|  | Home · Overviews · Examples

# QReadWriteLock Class Reference
[com.trolltech.qt.gui module]

The `QReadWriteLock` class provides read-write locking. More...

## Detailed Description

The `QReadWriteLock` class provides read-write locking.

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:

        QReadWriteLock lock;

        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. 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`, and `QSemaphore`.