QReadWriteLock Class
The QReadWriteLock class provides read-write locking. More...
| Header: | #include <QReadWriteLock> |
| qmake: | QT += core |
Note: All functions in this class are thread-safe.
Public Types
| enum | RecursionMode { Recursive, NonRecursive } |
Detailed Description
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 when constructed with QReadWriteLock::Recursive as 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, and QSemaphore.
Member Type Documentation
enum QReadWriteLock::RecursionMode
| Constant | Value | Description |
|---|---|---|
QReadWriteLock::Recursive | 1 | In this mode, a thread can lock the same QReadWriteLock multiple times. The QReadWriteLock won't be unlocked until a corresponding number of unlock() calls have been made. |
QReadWriteLock::NonRecursive | 0 | In this mode, a thread may only lock a QReadWriteLock once. |
This enum was introduced or modified in Qt 4.4.
See also QReadWriteLock().