Search code examples
c++qtqt4

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


Does anyone know how to check and see if a QMutex is locked, without using the function:

bool QMutex::tryLock()

The reason I don't want to use tryLock() is because it does two things:

  1. Check and see if the mutex is locked.
  2. If it's not locked then lock it.

For my purposes, I am not interested in performing this second step (locking the mutex).

I just want to know if it is locked or not.


Solution

  • 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.