Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

qt

qt4

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.

like image 378
Wes Avatar asked Dec 30 '11 19:12

Wes


2 Answers

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.

like image 145
Ernest Friedman-Hill Avatar answered Sep 20 '22 13:09

Ernest Friedman-Hill


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.

like image 30
Wes Avatar answered Sep 19 '22 13:09

Wes