Qt 4.8
Public Types | Public Functions | Private Functions | Properties | Friends | List of all members
QMutex Class Reference

The QMutex class provides access serialization between threads. More...

#include <qmutex.h>

Public Types

enum  RecursionMode { NonRecursive, Recursive }
 

Public Functions

void lock ()
 Locks the mutex. More...
 
void lockInline ()
 
 QMutex (RecursionMode mode=NonRecursive)
 Constructs a new mutex. More...
 
bool tryLock ()
 Attempts to lock the mutex. More...
 
bool tryLock (int timeout)
 Attempts to lock the mutex. More...
 
bool tryLockInline ()
 
void unlock ()
 Unlocks the mutex. More...
 
void unlockInline ()
 
 ~QMutex ()
 Destroys the mutex. More...
 

Private Functions

void lockInternal ()
 
void unlockInternal ()
 

Properties

QMutexDatad
 

Friends

class QWaitCondition
 
class QWaitConditionPrivate
 

Detailed Description

The QMutex class provides access serialization between threads.

Note
This class or function is threadsafe.

The purpose of a QMutex is to protect an object, data structure or section of code so that only one thread can access it at a time (this is similar to the Java synchronized keyword). It is usually best to use a mutex with a QMutexLocker since this makes it easy to ensure that locking and unlocking are performed consistently.

For example, say there is a method that prints a message to the user on two lines:

int number = 6;
void method1()
{
number *= 5;
number /= 4;
}
void method2()
{
number *= 3;
number /= 2;
}

If these two methods are called in succession, the following happens:

// method1()
number *= 5; // number is now 30
number /= 4; // number is now 7
// method2()
number *= 3; // number is now 21
number /= 2; // number is now 10

If these two methods are called simultaneously from two threads then the following sequence could result:

// Thread 1 calls method1()
number *= 5; // number is now 30
// Thread 2 calls method2().
//
// Most likely Thread 1 has been put to sleep by the operating
// system to allow Thread 2 to run.
number *= 3; // number is now 90
number /= 2; // number is now 45
// Thread 1 finishes executing.
number /= 4; // number is now 11, instead of 10

If we add a mutex, we should get the result we want:

QMutex mutex;
int number = 6;
void method1()
{
mutex.lock();
number *= 5;
number /= 4;
mutex.unlock();
}
void method2()
{
mutex.lock();
number *= 3;
number /= 2;
mutex.unlock();
}

Then only one thread can modify number at any given time and the result is correct. This is a trivial example, of course, but applies to any other case where things need to happen in a particular sequence.

When you call lock() in a thread, other threads that try to call lock() in the same place will block until the thread that got the lock calls unlock(). A non-blocking alternative to lock() is tryLock().

See also
QMutexLocker, QReadWriteLock, QSemaphore, QWaitCondition

Definition at line 60 of file qmutex.h.

Enumerations

◆ RecursionMode

  • Recursive In this mode, a thread can lock the same mutex multiple times and the mutex won't be unlocked until a corresponding number of unlock() calls have been made.
  • NonRecursive In this mode, a thread may only lock a mutex once.
See also
QMutex()
Enumerator
NonRecursive 
Recursive 

Definition at line 66 of file qmutex.h.

Constructors and Destructors

◆ QMutex()

QMutex::QMutex ( RecursionMode  mode = NonRecursive)
explicit

Constructs a new mutex.

Use the constructor that takes a RecursionMode parameter instead.

The mutex is created in an unlocked state.

If mode is QMutex::Recursive, a thread can lock the same mutex multiple times and the mutex won't be unlocked until a corresponding number of unlock() calls have been made. The default is QMutex::NonRecursive.

See also
lock(), unlock()

Definition at line 127 of file qmutex.cpp.

128  : d(new QMutexPrivate(mode))
129 { }
QMutexData * d
Definition: qmutex.h:98

◆ ~QMutex()

QMutex::~QMutex ( )

Destroys the mutex.

Warning
Destroying a locked mutex may result in undefined behavior.

Definition at line 136 of file qmutex.cpp.

137 { delete static_cast<QMutexPrivate *>(d); }
QMutexData * d
Definition: qmutex.h:98

Functions

◆ lock()

void QMutex::lock ( )

Locks the mutex.

If another thread has locked the mutex then this call will block until that thread has unlocked it.

Calling this function multiple times on the same mutex from the same thread is allowed if this mutex is a recursive mutex. If this mutex is a non-recursive mutex, this function will dead-lock when the mutex is locked recursively.

See also
unlock()

Definition at line 151 of file qmutex.cpp.

Referenced by QNetworkManagerEngine::activationFinished(), QNetworkManagerEngine::activeConnectionPropertiesChanged(), QIcdEngine::addConfiguration(), QNetworkConfigurationManagerPrivate::configurationAdded(), QConnmanEngine::configurationChange(), QNetworkConfigurationManagerPrivate::configurationChanged(), QNetworkConfigurationManagerPrivate::configurationRemoved(), QNetworkManagerEngine::deviceAdded(), QNetworkSessionPrivateImpl::do_open(), QGenericEngine::doRequestUpdate(), QIcdEngine::doRequestUpdate(), QNlaThread::fetchConfigurations(), QThreadPrivate::finish(), QNlaThread::forceUpdate(), QAudioOutputPrivate::freeBlocks(), QAudioInputPrivate::freeBlocks(), QIcdEngine::getIcdInitialState(), QNetworkSessionPrivateImpl::getStatistics(), QDeclarativeXmlQueryEngine::instance(), QNetworkManagerEngine::interfacePropertiesChanged(), QDeclarativePixmap::load(), QFreetypeFace::lock(), QWSDirectPainterSurface::lock(), locking_function(), QDeclarativePixmapReader::networkRequestDone(), QCoreWlanEngine::networksChanged(), QNlaEngine::networksChanged(), QNetworkManagerEngine::newAccessPoint(), QNetworkManagerEngine::parseConnection(), QWaitConditionPrivate::post(), QCoreApplication::postEvent(), QDBusMutexLocker::QDBusMutexLocker(), QDeclarativeWorkerScriptEngine::QDeclarativeWorkerScriptEngine(), qt_adopted_thread_watcher_function(), QDeclarativePixmapData::release(), QOrderedMutexLocker::relock(), QNetworkManagerEngine::removeAccessPoint(), QScanThread::run(), QWindowsPipeWriter::run(), QDeclarativeXmlQueryEngine::run(), QNlaThread::run(), QNativeWifiEngine::scanComplete(), QDnotifySignalThread::startNotify(), QNetworkSessionPrivateImpl::stateChange(), QFontEngineFT::stringToCMap(), QDeclarativeListModelWorkerAgent::sync(), QNetworkManagerEngine::updateAccessPoint(), QNlaThread::updateConfigurations(), QNetworkManagerEngine::updateConnection(), QNetworkSessionPrivateImpl::updateIdentifier(), QNetworkSessionPrivateImpl::updateState(), QWaitCondition::wait(), QDBusConnectionPrivate::waitForFinished(), QDeclarativePixmapReader::~QDeclarativePixmapReader(), QDeclarativeWorkerScriptEngine::~QDeclarativeWorkerScriptEngine(), QDeclarativeXmlQueryEngine::~QDeclarativeXmlQueryEngine(), QNlaThread::~QNlaThread(), and QWindowsPipeWriter::~QWindowsPipeWriter().

152 {
153  QMutexPrivate *d = static_cast<QMutexPrivate *>(this->d);
154  Qt::HANDLE self;
155 
156  if (d->recursive) {
157  self = QThread::currentThreadId();
158  if (d->owner == self) {
159  ++d->count;
160  Q_ASSERT_X(d->count != 0, "QMutex::lock", "Overflow in recursion counter");
161  return;
162  }
163 
164  bool isLocked = d->contenders.testAndSetAcquire(0, 1);
165  if (!isLocked) {
166  // didn't get the lock, wait for it
167  isLocked = d->wait();
168  Q_ASSERT_X(isLocked, "QMutex::lock",
169  "Internal error, infinite wait has timed out.");
170  }
171 
172  d->owner = self;
173  ++d->count;
174  Q_ASSERT_X(d->count != 0, "QMutex::lock", "Overflow in recursion counter");
175  return;
176  }
177 
178  bool isLocked = d->contenders.testAndSetAcquire(0, 1);
179  if (!isLocked) {
180  lockInternal();
181  }
182 }
QAtomicInt contenders
Definition: qmutex.h:158
QMutexData * d
Definition: qmutex.h:98
bool testAndSetAcquire(int expectedValue, int newValue)
Atomic test-and-set.
bool wait(int timeout=-1)
void * HANDLE
Definition: qnamespace.h:1671
const uint recursive
Definition: qmutex.h:159
#define Q_ASSERT_X(cond, where, what)
Definition: qglobal.h:1837
uint count
Definition: qmutex_p.h:80
Qt::HANDLE owner
Definition: qmutex_p.h:79
void lockInternal()
Definition: qmutex.cpp:454
static Qt::HANDLE currentThreadId()
Returns the thread handle of the currently executing thread.

◆ lockInline()

void QMutex::lockInline ( )
inline
Warning
This function is not part of the public interface. inline version of QMutex::lock()

Definition at line 198 of file qmutex.h.

Referenced by QMutexLocker::QMutexLocker(), and QOrderedMutexLocker::relock().

198 { lock(); }
void lock()
Locks the mutex.
Definition: qmutex.cpp:151

◆ lockInternal()

void QMutex::lockInternal ( )
private
Warning
This function is not part of the public interface. helper for lockInline()

Definition at line 454 of file qmutex.cpp.

Referenced by lock().

455 {
456  QMutexPrivate *d = static_cast<QMutexPrivate *>(this->d);
457 
458  if (QThread::idealThreadCount() == 1) {
459  // don't spin on single cpu machines
460  bool isLocked = d->wait();
461  Q_ASSERT_X(isLocked, "QMutex::lock",
462  "Internal error, infinite wait has timed out.");
463  Q_UNUSED(isLocked);
464  return;
465  }
466 
467  QElapsedTimer elapsedTimer;
468  elapsedTimer.start();
469  do {
470  qint64 spinTime = elapsedTimer.nsecsElapsed();
471  if (spinTime > d->maximumSpinTime) {
472  // didn't get the lock, wait for it, since we're not going to gain anything by spinning more
473  elapsedTimer.start();
474  bool isLocked = d->wait();
475  Q_ASSERT_X(isLocked, "QMutex::lock",
476  "Internal error, infinite wait has timed out.");
477  Q_UNUSED(isLocked);
478 
479  qint64 maximumSpinTime = d->maximumSpinTime;
480  qint64 averageWaitTime = d->averageWaitTime;
481  qint64 actualWaitTime = elapsedTimer.nsecsElapsed();
482  if (actualWaitTime < (QMutexPrivate::MaximumSpinTimeThreshold * 3 / 2)) {
483  // measure the wait times
484  averageWaitTime = d->averageWaitTime = qMin((averageWaitTime + actualWaitTime) / 2, qint64(QMutexPrivate::MaximumSpinTimeThreshold));
485  }
486 
487  // adjust the spin count when spinning does not benefit contention performance
489  // long waits, stop spinning
490  d->maximumSpinTime = 0;
491  } else {
492  // allow spinning if wait times decrease, but never spin more than the average wait time (otherwise we may perform worse)
493  d->maximumSpinTime = qBound(qint64(averageWaitTime * 3 / 2), maximumSpinTime / 2, qint64(QMutexPrivate::MaximumSpinTimeThreshold));
494  }
495  return;
496  }
497  // be a good citizen... yielding lets something else run if there is something to run, but may also relieve memory pressure if not
499  } while (d->contenders != 0 || !d->contenders.testAndSetAcquire(0, 1));
500 
501  // spinning is working, do not change the spin time (unless we are using much less time than allowed to spin)
502  qint64 maximumSpinTime = d->maximumSpinTime;
503  qint64 spinTime = elapsedTimer.nsecsElapsed();
504  if (spinTime < maximumSpinTime / 2) {
505  // we are using much less time than we need, adjust the limit
507  }
508 }
QAtomicInt contenders
Definition: qmutex.h:158
QMutexData * d
Definition: qmutex.h:98
Q_DECL_CONSTEXPR const T & qMin(const T &a, const T &b)
Definition: qglobal.h:1215
bool testAndSetAcquire(int expectedValue, int newValue)
Atomic test-and-set.
bool wait(int timeout=-1)
volatile qint64 maximumSpinTime
Definition: qmutex_p.h:77
The QElapsedTimer class provides a fast way to calculate elapsed times.
Definition: qelapsedtimer.h:53
static void yieldCurrentThread()
Yields execution of the current thread to another runnable thread, if any.
qint64 nsecsElapsed() const
Returns the number of nanoseconds since this QElapsedTimer was last started.
__int64 qint64
Definition: qglobal.h:942
#define Q_ASSERT_X(cond, where, what)
Definition: qglobal.h:1837
Q_DECL_CONSTEXPR const T & qBound(const T &min, const T &val, const T &max)
Definition: qglobal.h:1219
volatile qint64 averageWaitTime
Definition: qmutex_p.h:78
#define Q_UNUSED(x)
Indicates to the compiler that the parameter with the specified name is not used in the body of a fun...
Definition: qglobal.h:1729
void start()
Starts this timer.
static int idealThreadCount()
Returns the ideal number of threads that can be run on the system.

◆ tryLock() [1/2]

bool QMutex::tryLock ( )

Attempts to lock the mutex.

If the lock was obtained, this function returns true. If another thread has locked the mutex, this function returns false immediately.

If the lock was obtained, the mutex must be unlocked with unlock() before another thread can successfully lock it.

Calling this function multiple times on the same mutex from the same thread is allowed if this mutex is a recursive mutex. If this mutex is a non-recursive mutex, this function will always return false when attempting to lock the mutex recursively.

See also
lock(), unlock()

Definition at line 201 of file qmutex.cpp.

202 {
203  QMutexPrivate *d = static_cast<QMutexPrivate *>(this->d);
204  Qt::HANDLE self;
205 
206  if (d->recursive) {
207  self = QThread::currentThreadId();
208  if (d->owner == self) {
209  ++d->count;
210  Q_ASSERT_X(d->count != 0, "QMutex::tryLock", "Overflow in recursion counter");
211  return true;
212  }
213 
214  bool isLocked = d->contenders.testAndSetAcquire(0, 1);
215  if (!isLocked) {
216  // some other thread has the mutex locked, or we tried to
217  // recursively lock an non-recursive mutex
218  return isLocked;
219  }
220 
221  d->owner = self;
222  ++d->count;
223  Q_ASSERT_X(d->count != 0, "QMutex::tryLock", "Overflow in recursion counter");
224  return isLocked;
225  }
226 
227  return d->contenders.testAndSetAcquire(0, 1);
228 }
QAtomicInt contenders
Definition: qmutex.h:158
QMutexData * d
Definition: qmutex.h:98
bool testAndSetAcquire(int expectedValue, int newValue)
Atomic test-and-set.
void * HANDLE
Definition: qnamespace.h:1671
const uint recursive
Definition: qmutex.h:159
#define Q_ASSERT_X(cond, where, what)
Definition: qglobal.h:1837
uint count
Definition: qmutex_p.h:80
Qt::HANDLE owner
Definition: qmutex_p.h:79
static Qt::HANDLE currentThreadId()
Returns the thread handle of the currently executing thread.

◆ tryLock() [2/2]

bool QMutex::tryLock ( int  timeout)

Attempts to lock the mutex.

This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.

This function returns true if the lock was obtained; otherwise it returns false. If another thread has locked the mutex, this function will wait for at most timeout milliseconds for the mutex to become available.

Note: Passing a negative number as the timeout is equivalent to calling lock(), i.e. this function will wait forever until mutex can be locked if timeout is negative.

If the lock was obtained, the mutex must be unlocked with unlock() before another thread can successfully lock it.

Calling this function multiple times on the same mutex from the same thread is allowed if this mutex is a recursive mutex. If this mutex is a non-recursive mutex, this function will always return false when attempting to lock the mutex recursively.

See also
lock(), unlock()

Definition at line 256 of file qmutex.cpp.

257 {
258  QMutexPrivate *d = static_cast<QMutexPrivate *>(this->d);
259  Qt::HANDLE self;
260 
261  if (d->recursive) {
262  self = QThread::currentThreadId();
263  if (d->owner == self) {
264  ++d->count;
265  Q_ASSERT_X(d->count != 0, "QMutex::tryLock", "Overflow in recursion counter");
266  return true;
267  }
268 
269  bool isLocked = d->contenders.testAndSetAcquire(0, 1);
270  if (!isLocked) {
271  // didn't get the lock, wait for it
272  isLocked = d->wait(timeout);
273  if (!isLocked)
274  return false;
275  }
276 
277  d->owner = self;
278  ++d->count;
279  Q_ASSERT_X(d->count != 0, "QMutex::tryLock", "Overflow in recursion counter");
280  return true;
281  }
282 
283  return (d->contenders.testAndSetAcquire(0, 1)
284  // didn't get the lock, wait for it
285  || d->wait(timeout));
286 }
QAtomicInt contenders
Definition: qmutex.h:158
QMutexData * d
Definition: qmutex.h:98
bool testAndSetAcquire(int expectedValue, int newValue)
Atomic test-and-set.
bool wait(int timeout=-1)
void * HANDLE
Definition: qnamespace.h:1671
const uint recursive
Definition: qmutex.h:159
#define Q_ASSERT_X(cond, where, what)
Definition: qglobal.h:1837
uint count
Definition: qmutex_p.h:80
Qt::HANDLE owner
Definition: qmutex_p.h:79
static Qt::HANDLE currentThreadId()
Returns the thread handle of the currently executing thread.

◆ tryLockInline()

bool QMutex::tryLockInline ( )
inline
Warning
This function is not part of the public interface. inline version of QMutex::tryLock()

Definition at line 197 of file qmutex.h.

Referenced by QOrderedMutexLocker::relock().

197 { return tryLock(); }
bool tryLock()
Attempts to lock the mutex.
Definition: qmutex.cpp:201

◆ unlock()

void QMutex::unlock ( )

Unlocks the mutex.

Attempting to unlock a mutex in a different thread to the one that locked it results in an error. Unlocking a mutex that is not locked results in undefined behavior.

See also
lock()

Definition at line 296 of file qmutex.cpp.

Referenced by QNetworkManagerEngine::activationFinished(), QNetworkManagerEngine::activeConnectionPropertiesChanged(), QIcdEngine::addConfiguration(), QNetworkConfigurationManagerPrivate::configurationAdded(), QConnmanEngine::configurationChange(), QNetworkConfigurationManagerPrivate::configurationChanged(), QNetworkConfigurationManagerPrivate::configurationRemoved(), QNetworkManagerEngine::deviceAdded(), QNetworkSessionPrivateImpl::do_open(), QGenericEngine::doRequestUpdate(), QIcdEngine::doRequestUpdate(), QNlaThread::fetchConfigurations(), QThreadPrivate::finish(), QNlaThread::forceUpdate(), QAudioOutputPrivate::freeBlocks(), QAudioInputPrivate::freeBlocks(), QIcdEngine::getIcdInitialState(), QNetworkSessionPrivateImpl::getStatistics(), QDeclarativeXmlQueryEngine::instance(), QNetworkManagerEngine::interfacePropertiesChanged(), QDeclarativePixmap::load(), locking_function(), QDeclarativePixmapReader::networkRequestDone(), QCoreWlanEngine::networksChanged(), QNlaEngine::networksChanged(), QNetworkManagerEngine::newAccessPoint(), QNetworkManagerEngine::parseConnection(), QWaitConditionPrivate::post(), QCoreApplication::postEvent(), QDeclarativeWorkerScriptEngine::QDeclarativeWorkerScriptEngine(), qt_adopted_thread_watcher_function(), QDeclarativePixmapData::release(), QOrderedMutexLocker::relock(), QNetworkManagerEngine::removeAccessPoint(), QScanThread::run(), QWindowsPipeWriter::run(), QDeclarativeXmlQueryEngine::run(), QNlaThread::run(), QNativeWifiEngine::scanComplete(), QDnotifySignalThread::startNotify(), QNetworkSessionPrivateImpl::stateChange(), QFontEngineFT::stringToCMap(), QDeclarativeListModelWorkerAgent::sync(), QFreetypeFace::unlock(), QMutexUnlocker::unlock(), QWSDirectPainterSurface::unlock(), QNetworkManagerEngine::updateAccessPoint(), QNlaThread::updateConfigurations(), QNetworkManagerEngine::updateConnection(), QNetworkSessionPrivateImpl::updateIdentifier(), QNetworkSessionPrivateImpl::updateState(), QWaitCondition::wait(), QDBusConnectionPrivate::waitForFinished(), QDBusMutexLocker::~QDBusMutexLocker(), QDeclarativePixmapReader::~QDeclarativePixmapReader(), QDeclarativeWorkerScriptEngine::~QDeclarativeWorkerScriptEngine(), QDeclarativeXmlQueryEngine::~QDeclarativeXmlQueryEngine(), QNlaThread::~QNlaThread(), and QWindowsPipeWriter::~QWindowsPipeWriter().

297 {
298  QMutexPrivate *d = static_cast<QMutexPrivate *>(this->d);
299  if (d->recursive) {
300  if (!--d->count) {
301  d->owner = 0;
302  if (!d->contenders.testAndSetRelease(1, 0))
303  d->wakeUp();
304  }
305  } else {
306  if (!d->contenders.testAndSetRelease(1, 0))
307  d->wakeUp();
308  }
309 }
QAtomicInt contenders
Definition: qmutex.h:158
QMutexData * d
Definition: qmutex.h:98
bool testAndSetRelease(int expectedValue, int newValue)
Atomic test-and-set.
const uint recursive
Definition: qmutex.h:159
uint count
Definition: qmutex_p.h:80
Qt::HANDLE owner
Definition: qmutex_p.h:79

◆ unlockInline()

void QMutex::unlockInline ( )
inline
Warning
This function is not part of the public interface. inline version of QMutex::unlock()

Definition at line 196 of file qmutex.h.

Referenced by QMetaObjectPrivate::disconnectHelper(), QOrderedMutexLocker::unlock(), and QObject::~QObject().

196 { unlock(); }
void unlock()
Unlocks the mutex.
Definition: qmutex.cpp:296

◆ unlockInternal()

void QMutex::unlockInternal ( )
private
Warning
This function is not part of the public interface.

Definition at line 513 of file qmutex.cpp.

514 {
515  static_cast<QMutexPrivate *>(d)->wakeUp();
516 }
QMutexData * d
Definition: qmutex.h:98

Friends and Related Functions

◆ QWaitCondition

friend class QWaitCondition
friend

Definition at line 62 of file qmutex.h.

◆ QWaitConditionPrivate

Definition at line 63 of file qmutex.h.

Properties

◆ d

QMutexData* QMutex::d
private

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