Nyaruko
Nyaruko

Reputation: 4499

Is it ok to unlock a mutex twice in Qt 5.4?

The code is as following:

waitmutex.lock(); //waitmutex is a QMutex
int tout=4000;
if(!waitc.wait(&waitmutex,tout))//waitc is a QWaitCondition
{
    waitmutex.unlock(); // unlock first time
    mutex.lock();
    if(tileCacheQueue.count()==0)
    {
        mutex.unlock();
        break;
    }
    mutex.unlock();
}
waitmutex.unlock();// unlock the second time possibly?

Will the code possibly results in the waitmutex to be unlocked twice? Is this a problem in Qt?

Upvotes: 0

Views: 887

Answers (1)

MrEricSir
MrEricSir

Reputation: 8242

According to the documentation this is undefined behavior:

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.

Emphasis mine.

While I'm not entirely certain what your code is doing, you should consider using QMutexLocker for one or both mutexes to make your code exception safe.

Upvotes: 4

Related Questions