QWriteLocker Class

The QWriteLocker class is a convenience class that simplifies locking and unlocking read-write locks for write access. More...

Header: #include <QWriteLocker>
CMake: find_package(Qt6 COMPONENTS Core REQUIRED)
target_link_libraries(mytarget PRIVATE Qt6::Core)
qmake: QT += core

Note: All functions in this class are thread-safe.

Public Functions

QWriteLocker(QReadWriteLock *lock)
~QWriteLocker()
QReadWriteLock *readWriteLock() const
void relock()
void unlock()

Detailed Description

The purpose of QWriteLocker (and QReadLocker) is to simplify QReadWriteLock locking and unlocking. Locking and unlocking statements or in exception handling code is error-prone and difficult to debug. QWriteLocker can be used in such situations to ensure that the state of the lock is always well-defined.

Here's an example that uses QWriteLocker to lock and unlock a read-write lock for writing:

 QReadWriteLock lock;

 void writeData(const QByteArray &data)
 {
     QWriteLocker locker(&lock);
     ...
 }

It is equivalent to the following code:

 QReadWriteLock lock;

 void writeData(const QByteArray &data)
 {
     lock.lockForWrite();
     ...
     lock.unlock();
 }

The QMutexLocker documentation shows examples where the use of a locker object greatly simplifies programming.

See also QReadLocker and QReadWriteLock.

Member Function Documentation

QWriteLocker::QWriteLocker(QReadWriteLock *lock)

Constructs a QWriteLocker and locks lock for writing. The lock will be unlocked when the QWriteLocker is destroyed. If lock is zero, QWriteLocker does nothing.

See also QReadWriteLock::lockForWrite().

QWriteLocker::~QWriteLocker()

Destroys the QWriteLocker and unlocks the lock that was passed to the constructor.

See also QReadWriteLock::unlock().

QReadWriteLock *QWriteLocker::readWriteLock() const

Returns a pointer to the read-write lock that was passed to the constructor.

void QWriteLocker::relock()

Relocks an unlocked lock.

See also unlock().

void QWriteLocker::unlock()

Unlocks the lock associated with this locker.

See also QReadWriteLock::unlock().