c++qtmutexrecursive-mutex

How to use recursive QMutex


I'm trying to use a recursive QMutex, i read the QMutex Class Reference but i not understand how to do it, can someone give me an example? I need some way to lock QMutex that can be unlocked after or before the lock method is called. If recursive mutex is not the way is there any other way?


Solution

  • To create a recursive QMutex you simply pass QMutex::Recursive at construction time, for instance:

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

    Recursive means that you can lock several times the mutex from the same thread, you don't have to unlock it. If I understood well your question that's what you want.

    Be careful, if you lock recursively you must call unlock the same amount of times. A better way to lock/unlock a mutex is using a QMutexLocker

    #include <QMutexLocker>
    
    QMutex mutex(QMutex::Recursive);
    int number = 6;
    
    void method1()
    {
        QMutexLocker locker(&mutex); // Here mutex is locked
        number *= 5;
        // Here locker goes out of scope.
        // When locker is destroyed automatically unlocks mutex
    }
    
    void method2()
    {
        QMutexLocker locker(&mutex);
        number *= 3;
    }