Qt 4.8
Public Functions | Properties | List of all members
QMutexLocker Class Reference

The QMutexLocker class is a convenience class that simplifies locking and unlocking mutexes. More...

#include <qmutex.h>

Public Functions

QMutexmutex () const
 Returns a pointer to the mutex that was locked in the constructor. More...
 
 QMutexLocker (QMutex *m)
 Constructs a QMutexLocker and locks mutex. More...
 
void relock ()
 Relocks an unlocked mutex locker. More...
 
void unlock ()
 Unlocks this mutex locker. More...
 
 ~QMutexLocker ()
 Destroys the QMutexLocker and unlocks the mutex that was locked in the constructor. More...
 

Properties

quintptr val
 

Detailed Description

The QMutexLocker class is a convenience class that simplifies locking and unlocking mutexes.

Note
This class or function is threadsafe.

Locking and unlocking a QMutex in complex functions and statements or in exception handling code is error-prone and difficult to debug. QMutexLocker can be used in such situations to ensure that the state of the mutex is always well-defined.

QMutexLocker should be created within a function where a QMutex needs to be locked. The mutex is locked when QMutexLocker is created. You can unlock and relock the mutex with unlock() and relock(). If locked, the mutex will be unlocked when the QMutexLocker is destroyed.

For example, this complex function locks a QMutex upon entering the function and unlocks the mutex at all the exit points:

int complexFunction(int flag)
{
int retVal = 0;
switch (flag) {
case 0:
case 1:
retVal = moreComplexFunction(flag);
break;
case 2:
{
int status = anotherFunction();
if (status < 0) {
return -2;
}
retVal = status + flag;
}
break;
default:
if (flag > 10) {
return -1;
}
break;
}
return retVal;
}

This example function will get more complicated as it is developed, which increases the likelihood that errors will occur.

Using QMutexLocker greatly simplifies the code, and makes it more readable:

int complexFunction(int flag)
{
QMutexLocker locker(&mutex);
int retVal = 0;
switch (flag) {
case 0:
case 1:
return moreComplexFunction(flag);
case 2:
{
int status = anotherFunction();
if (status < 0)
return -2;
retVal = status + flag;
}
break;
default:
if (flag > 10)
return -1;
break;
}
return retVal;
}

Now, the mutex will always be unlocked when the QMutexLocker object is destroyed (when the function returns since locker is an auto variable).

The same principle applies to code that throws and catches exceptions. An exception that is not caught in the function that has locked the mutex has no way of unlocking the mutex before the exception is passed up the stack to the calling function.

QMutexLocker also provides a mutex() member function that returns the mutex on which the QMutexLocker is operating. This is useful for code that needs access to the mutex, such as QWaitCondition::wait(). For example:

class SignalWaiter
{
private:
QMutexLocker locker;
public:
SignalWaiter(QMutex *mutex)
: locker(mutex)
{
}
void waitForSignal()
{
...
while (!signalled)
waitCondition.wait(locker.mutex());
...
}
};
See also
QReadLocker, QWriteLocker, QMutex

Definition at line 101 of file qmutex.h.

Constructors and Destructors

◆ QMutexLocker()

QMutexLocker::QMutexLocker ( QMutex mutex)
inlineexplicit

Constructs a QMutexLocker and locks mutex.

The mutex will be unlocked when the QMutexLocker is destroyed. If mutex is zero, QMutexLocker does nothing.

See also
QMutex::lock()

Definition at line 104 of file qmutex.h.

105  {
106  Q_ASSERT_X((reinterpret_cast<quintptr>(m) & quintptr(1u)) == quintptr(0),
107  "QMutexLocker", "QMutex pointer is misaligned");
108  if (m) {
109  m->lockInline();
110  val = reinterpret_cast<quintptr>(m) | quintptr(1u);
111  } else {
112  val = 0;
113  }
114  }
QIntegerForSizeof< void * >::Unsigned quintptr
Definition: qglobal.h:986
quintptr val
Definition: qmutex.h:152
quint16 u
#define Q_ASSERT_X(cond, where, what)
Definition: qglobal.h:1837

◆ ~QMutexLocker()

QMutexLocker::~QMutexLocker ( )
inline

Destroys the QMutexLocker and unlocks the mutex that was locked in the constructor.

See also
QMutex::unlock()

Definition at line 115 of file qmutex.h.

115 { unlock(); }
void unlock()
Unlocks this mutex locker.
Definition: qmutex.h:117

Functions

◆ mutex()

QMutex * QMutexLocker::mutex ( ) const
inline

Returns a pointer to the mutex that was locked in the constructor.

Definition at line 140 of file qmutex.h.

Referenced by QSemaphore::acquire(), QThreadPrivate::finish(), QThreadPoolThread::run(), QThread::start(), QSemaphore::tryAcquire(), QThread::wait(), and QThreadPoolPrivate::waitForDone().

141  {
142  return reinterpret_cast<QMutex *>(val & ~quintptr(1u));
143  }
QIntegerForSizeof< void * >::Unsigned quintptr
Definition: qglobal.h:986
The QMutex class provides access serialization between threads.
Definition: qmutex.h:60
quintptr val
Definition: qmutex.h:152
quint16 u

◆ relock()

void QMutexLocker::relock ( )
inline

Relocks an unlocked mutex locker.

See also
unlock()

Definition at line 125 of file qmutex.h.

Referenced by QMetaObject::activate(), QNetworkManagerEngine::activationFinished(), QNetworkManagerEngine::activeConnectionPropertiesChanged(), QIcdEngine::addConfiguration(), QConnmanEngine::addServiceConfiguration(), QIcdEngine::asyncUpdateConfigurationsSlot(), QConnmanEngine::configurationChange(), QIcdEngine::connectionStateSignalsSlot(), QNativeWifiEngine::connectToId(), QCoreWlanEngine::disconnectFromId(), QGenericEngine::doRequestUpdate(), QEventLoop::exec(), QThread::exec(), QThreadPrivate::finish(), QScanThread::foundNetwork(), QIcdEngine::icdServiceOwnerChanged(), initDefaultPaths(), QNetworkManagerEngine::initialize(), QIcdEngine::initialize(), QNetworkManagerEngine::interfacePropertiesChanged(), QCoreWlanEngine::networksChanged(), QNlaEngine::networksChanged(), QDeclarativePixmapReader::processJobs(), QDeclarativeXmlQueryEngine::processJobs(), QNetworkManagerEngine::removeAccessPoint(), QConnmanEngine::removeConfiguration(), QWindowsFileSystemWatcherEngine::removePaths(), QIcdEngine::requestUpdate(), QThreadPoolPrivate::reset(), QThreadPoolThread::run(), QWindowsFileSystemWatcherEngineThread::run(), QNativeWifiEngine::scanComplete(), QCoreApplicationPrivate::sendPostedEvents(), QThreadPoolPrivate::startFrontRunnable(), and QThread::~QThread().

126  {
127  if (val) {
128  if ((val & quintptr(1u)) == quintptr(0u)) {
129  mutex()->lockInline();
130  val |= quintptr(1u);
131  }
132  }
133  }
QIntegerForSizeof< void * >::Unsigned quintptr
Definition: qglobal.h:986
quintptr val
Definition: qmutex.h:152
quint16 u
void lockInline()
Definition: qmutex.h:198
QMutex * mutex() const
Returns a pointer to the mutex that was locked in the constructor.
Definition: qmutex.h:140

◆ unlock()

void QMutexLocker::unlock ( )
inline

Unlocks this mutex locker.

You can use relock() to lock it again. It does not need to be locked when destroyed.

See also
relock()

Definition at line 117 of file qmutex.h.

Referenced by QMetaObject::activate(), QNetworkManagerEngine::activationFinished(), QNetworkManagerEngine::activeConnectionPropertiesChanged(), QIcdEngine::addConfiguration(), QCoreApplication::addLibraryPath(), QConnmanEngine::addServiceConfiguration(), QIcdEngine::addSessionConfiguration(), QIcdEngine::asyncUpdateConfigurationsSlot(), QTextCodec::availableCodecs(), QTextCodec::availableMibs(), QConnmanEngine::configurationChange(), QIcdEngine::connectionStateSignalsSlot(), QCoreWlanEngine::connectToId(), QNativeWifiEngine::connectToId(), QIcdEngine::deleteConfiguration(), QUrl::detach(), QCoreWlanEngine::disconnectFromId(), QNativeWifiEngine::disconnectFromId(), QGenericEngine::doRequestUpdate(), QBBEngine::doRequestUpdate(), QCoreWlanEngine::doRequestUpdate(), QIcdEngine::doRequestUpdate(), QDeclarativeListModelWorkerAgent::event(), QEventLoop::exec(), QThread::exec(), QThreadPrivate::finish(), QScanThread::foundNetwork(), QIcdEngine::getIcdInitialState(), QDeclarativeEnginePrivate::getImageFromProvider(), QDeclarativeEnginePrivate::getImageProviderType(), QDeclarativeEnginePrivate::getPixmapFromProvider(), QIcdEngine::icdServiceOwnerChanged(), initDefaultPaths(), QNetworkManagerEngine::initialize(), QIcdEngine::initialize(), QNetworkManagerEngine::interfacePropertiesChanged(), QUrl::isParentOf(), QCoreWlanEngine::networksChanged(), QNlaEngine::networksChanged(), QNetworkManagerEngine::newAccessPoint(), QNetworkManagerEngine::newConnection(), QDBusConnectionPrivate::processFinishedCall(), QDeclarativePixmapReader::processJobs(), QDeclarativeXmlQueryEngine::processJobs(), QNetworkManagerEngine::removeAccessPoint(), QBBEngine::removeConfiguration(), QConnmanEngine::removeConfiguration(), QNetworkManagerEngine::removeConnection(), QWindowsFileSystemWatcherEngine::removePaths(), QPollingFileSystemWatcherEngine::removePaths(), QCoreApplication::removePostedEvents(), QNativeWifiEngine::requestUpdate(), QIcdEngine::requestUpdate(), QThreadPoolPrivate::reset(), QThreadPoolThread::run(), QWindowsFileSystemWatcherEngineThread::run(), QFileInfoGatherer::run(), QNativeWifiEngine::scanComplete(), QCoreApplicationPrivate::sendPostedEvents(), QCoreApplication::setLibraryPaths(), QThreadPoolPrivate::startFrontRunnable(), QNetworkSessionPrivateImpl::syncStateWithInterface(), QNetworkManagerEngine::updateAccessPoint(), QBBEngine::updateConfiguration(), QNetworkConfigurationManagerPrivate::updateConfigurations(), QNetworkManagerEngine::updateConnection(), QFileInfoGatherer::~QFileInfoGatherer(), and QThread::~QThread().

118  {
119  if ((val & quintptr(1u)) == quintptr(1u)) {
120  val &= ~quintptr(1u);
121  mutex()->unlockInline();
122  }
123  }
QIntegerForSizeof< void * >::Unsigned quintptr
Definition: qglobal.h:986
quintptr val
Definition: qmutex.h:152
quint16 u
void unlockInline()
Definition: qmutex.h:196
QMutex * mutex() const
Returns a pointer to the mutex that was locked in the constructor.
Definition: qmutex.h:140

Properties

◆ val

quintptr QMutexLocker::val
private

Definition at line 152 of file qmutex.h.


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