Search code examples
multithreadingqt4qmutex

QMutex lock in one thread and unlock in the other thread


Am I allowed to use the QMutex in the strange way: lock the QMutex in one thread, then unlock it in the other thread?


Solution

  • According to the documentation of QMutex this results in an error:

    Attempting to unlock a mutex in a different thread to the one that locked it results in an error.

    But instead of a QMutex you can use a QSemaphore as a binary semaphore, to achieve the wanted behavior.

    //create
    QSemaphore semaphore(1);
    
    //lock in thread 1
    semaphore.acquire();
    
    //unlock in thread 2
    semaphore.release();