QMutexLocker Class
template <typename MutexT> class QMutexLocker
The QMutexLocker class is a convenience class that simplifies locking and unlocking mutexes. More…
| Header | #include <QMutexLocker> |
|---|---|
| CMake | target_link_libraries(app PRIVATE Nt::Core) |
| Module | Nt Core C++ Classes |
List of all members, including inherited members
Public Functions
| QMutexLocker(MutexT *mtx) | |
| QMutexLocker(QMutexLocker &&o) | |
| QMutexLocker & | operator=(QMutexLocker &&o) |
| void | swap(QMutexLocker &other) |
| ~QMutexLocker() | |
| void | unlock() |
| void | relock() |
| MutexT * | mutex() const |
| bool | isLocked() const |
Detailed Description
A QMutexLocker locks the mutex it is given when it is constructed and unlocks it when it is destroyed, so the mutex is released on every path out of a scope, including exceptions and early returns:
QMutex mutex;
int complexFunction(int flag)
{
QMutexLocker locker(&mutex);
if (flag < 0)
return 0;
return flag * 2;
}
The class works with any type that provides lock() and unlock(), such as QMutex and QRecursiveMutex. A QMutexLocker can be moved but not copied.
See also QMutex, QRecursiveMutex, QReadLocker and QWriteLocker.
Differences from Qt
A null pointer is accepted and results in a locker that never locks anything. The locker works with any type that has lock() and unlock(), not only the Nt mutex classes.
Member Function Documentation
QMutexLocker::QMutexLocker(MutexT *mtx)
Constructs a QMutexLocker and locks mtx. The mutex is unlocked when the locker is destroyed. If mtx is nullptr, the locker does nothing.
See also unlock().
QMutexLocker::QMutexLocker(QMutexLocker &&o)
Move-constructs a locker from o, taking over the mutex and its locked state. o no longer refers to a mutex afterwards.
QMutexLocker::~QMutexLocker()
Destroys the locker and unlocks the mutex if it is currently locked by this locker.
bool QMutexLocker::isLocked() const
Returns true if this locker currently holds the mutex; otherwise returns false.
See also unlock() and relock().
MutexT * QMutexLocker::mutex() const
Returns the mutex this locker operates on, or nullptr if there is none.
QMutexLocker & QMutexLocker::operator=(QMutexLocker &&o)
Move-assigns o to this locker. The mutex this locker held is unlocked first; then the locker takes over the mutex and locked state of o, which no longer refers to a mutex.
void QMutexLocker::relock()
Relocks the mutex after it was unlocked with unlock(). Does nothing if the mutex is already locked by this locker.
See also unlock().
void QMutexLocker::swap(QMutexLocker &other)
Swaps the mutex and the locked state of this locker with those of other.
void QMutexLocker::unlock()
Unlocks the mutex if this locker holds it.
See also relock().