I want to find out if a pthread lock variable is locked or not. One simple approach is to use a trylock as shown below
pthread_mutex_t lockVar;
if(pthread_mutex_trylock(&lockVar) == 0)
{
//lock was successful
pthread_mutex_unlock(&lockVar);
}
else
{
//someone else holds the lock
}
How do I do the same thing without obtaining a lock?
When you have multiple executions happening concurrently, there is no notion of "simultaneity". Events cannot be given a global order in time, except for when explicit synchronizations happen. There is no property that's observable from within the language that can observe any kind of ordering in general.
Specifically, the question "is that mutex over there locked" is meaningless. It has no answer upon which you can act. Whatever the fictitious answer is, the state of the mutex can change right after. There is nothing you can do with an answer like "yes, it's locked" (it might become unlocked at the same time), or "no, it's unlocked" (it may get locked before you get there).
The only thing you can do with a mutex is try to lock it. You either fail, and thus know that it was locked, or you succeed and thus know that it wasn't, and now you have the lock.
Regardless of what you want to do with the result, the way you're doing it right now is the only way. You cannot simply query whether a mutex is locked without locking it. If you want a synchronization primitive for which you can query the status without modifying it, POSIX semaphores would be a possibility. A binary semaphore can serve as a lock (although it lacks the concept of an owner, which may be a problem for you if you need recursive locking) and sem_getvalue
can determine whether or not the semaphore is "locked" at a single moment in time.
As for whether the question you're asking is even meaningful, Kerrek has already told you it's usually not. Here are a few possible, minimally-useful pieces of information you could gather from negative or positive results:
Negative:
Positive:
But for the most part, "is the mutex locked?" is not a useful question.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With