QMutex Class

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

Header: #include <QMutex>
qmake: QT += core
Inherited By:

QRecursiveMutex

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

Public Types

enum RecursionMode { Recursive, NonRecursive }

Public Functions

QMutex(QMutex::RecursionMode mode)
QMutex()
~QMutex()
bool isRecursive() const
void lock()
bool tryLock(int timeout = 0)
bool try_lock()
bool try_lock_for(std::chrono::duration<Rep, Period> duration)
bool try_lock_until(std::chrono::time_point<Clock, Duration> timePoint)
void unlock()

Detailed Description

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().

QMutex is optimized to be fast in the non-contended case. A non-recursive QMutex will not allocate memory if there is no contention on that mutex. It is constructed and destroyed with almost no overhead, which means it is fine to have many mutexes as part of other classes.

See also QRecursiveMutex, QMutexLocker, QReadWriteLock, QSemaphore, and QWaitCondition.

Member Type Documentation

enum QMutex::RecursionMode

ConstantValueDescription
QMutex::Recursive1In 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. You should use QRecursiveMutex for this use-case.
QMutex::NonRecursive0In this mode, a thread may only lock a mutex once.

See also QMutex() and QRecursiveMutex.

Member Function Documentation

QMutex::QMutex(QMutex::RecursionMode mode)

Constructs a new mutex. 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. Otherwise a thread may only lock a mutex once. The default is QMutex::NonRecursive.

Recursive mutexes are slower and take more memory than non-recursive ones.

See also lock() and unlock().

QMutex::QMutex()

Constructs a new mutex. The mutex is created in an unlocked state.

QMutex::~QMutex()

Destroys the mutex.

Warning: Destroying a locked mutex may result in undefined behavior.

bool QMutex::isRecursive() const

Returns true if the mutex is recursive.

This function was introduced in Qt 5.7.

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().

bool QMutex::tryLock(int timeout = 0)

Attempts to lock the mutex. 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() and unlock().

bool QMutex::try_lock()

Attempts to lock the mutex. This function returns true if the lock was obtained; otherwise it returns false.

This function is provided for compatibility with the Standard Library concept Lockable. It is equivalent to tryLock().

The function returns true if the lock was obtained; otherwise it returns false

This function was introduced in Qt 5.8.

template <typename Rep, typename Period> bool QMutex::try_lock_for(std::chrono::duration<Rep, Period> duration)

Attempts to lock the mutex. 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 least duration for the mutex to become available.

Note: Passing a negative duration as the duration is equivalent to calling try_lock(). This behavior differs from tryLock().

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.

This function was introduced in Qt 5.8.

See also lock() and unlock().

template <typename Clock, typename Duration> bool QMutex::try_lock_until(std::chrono::time_point<Clock, Duration> timePoint)

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

Note: Passing a timePoint which has already passed is equivalent to calling try_lock(). This behavior differs from tryLock().

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.

This function was introduced in Qt 5.8.

See also lock() and 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().