How can you tell if a QMutex is locked or not?

OK, I'm guessing there is no real way to do what I'm asking without actually using tryLock().

This could be accomplished with the following code:

bool is_locked = true;

if( a_mutex.tryLock() )
{
    a_mutex.unlock();
    is_locked = false;
}

if( is_locked )
{
    ...
}

As you can see, it unlocks the QMutex, "a_mutex", if it was able to lock it.

Of course, this is not a perfect solution, as by the time it hits the 2nd if statement, the mutex's status could have changed.


Maybe a QSemaphore with one permit? The available() method may give you what you need.


Trying to lock a mutex is by definition the only way to tell if it's locked; otherwise when this imaginary function returned, how would you know if the mutex was still locked? It may have become unlocked while the function was returning; or more importantly, without performing all the cache-flushing and syncronization necessary to lock it, you couldn't actually be sure if it was locked or not.

Tags:

C++

Qt

Qt4